SQL从组中按最高值选择一行

时间:2019-06-07 07:35:13

标签: sql sql-server greatest-n-per-group

我正在尝试通过其他列的不同选择来选择组中的最高值(计算得出)

根据下面的表格数据,我要选择数量最多的行(数量计划),并选择不同的Len和Wid

表数据如下

+-----------+-----------+---------+---------+------------+---------+
|   Ident   |   Name    | Len     |   Wid   |      Qty   |    Plan |
+-----------+-----------+---------+---------+------------+---------+
|  12345    | Name1     | 1500    |    1000 |         20 |       5 |
|  23456    | Name1     | 1500    |    1000 |         30 |      13 |
|  34567    | Name1     | 2500    |    1000 |         10 |       2 |
|  45678    | Name1     | 2500    |    1000 |         10 |       4 |
|  56789    | Name1     | 1500    |    1200 |         20 |       3 |
|  00001    | Name2     | 1500    |    1200 |         10 |       6 |
|  00002    | Name2     | 1500    |    1200 |         20 |       7 |
|  00003    | Name3     | 1500    |    1200 |         30 |       5 |
|  00004    | Name3     | 1500    |    1200 |         40 |       4 |
+-----------+-----------+---------+---------+------------+---------+

我的查询无法删除“较低”的值:

select a.Ident ,a.Name, a.Len,a.Wid, a.Qnt-a.Plan as Amount
from table a
join (select ident, max(Qnt - Plan) Amount
      from table
      where Name = 'Name1'
      group by Ident, Len, Wid) b
  on b.Ident = a.Ident and b.Amount = a.Qnt-a.Plan
order by Amount desc

题外话:为什么我不能使用-> b.Amount = a.Amount(他不知道a.Amount)???

我想要的选择应如下所示:

+-----------+-----------+---------+---------+------------+
|   Ident   |   Name    | Len     |   Wid   |   Amount   |
+-----------+-----------+---------+---------+------------+
|  56789    | Name1     | 1500    |    1200 |         18 |
|  23456    | Name1     | 1500    |    1000 |         17 |
|  34567    | Name1     | 2500    |    1000 |          8 |
+-----------+-----------+---------+---------+------------+

非常感谢

2 个答案:

答案 0 :(得分:1)

尚不清楚您使用的是哪种数据库,但此解决方案应可在任何数据库上使用:

SELECT tab.Ident,
       tab.Name,
       tab.Len,
       tab.Wid,
       (tab.Qty - tab.Plan) AS Amount
FROM   (SELECT   Name,
                 Len,
                 Wid,
                 MAX(Qty-Plan) AS Amount
        FROM     my_table
        GROUP BY Name,
                 Len,
                 Wid
       ) AS grouped
JOIN   my_table tab
  ON   grouped.Name = tab.Name
 AND   grouped.Len = tab.Len
 AND   grouped.Wid = tab.Wid
 AND   grouped.Amount = (tab.Qty - tab.Plan)
 AND   tab.Name = 'Name1'

答案 1 :(得分:1)

另一种方法,使用窗口函数来简化操作:

SELECT ident, name, len, wid, qnt - [plan] AS amount
FROM  (SELECT *, row_number() OVER (PARTITION BY len, wid ORDER BY qnt - [plan] DESC) AS rn
       FROM test WHERE name = 'Name1') AS sq
WHERE rn = 1
ORDER BY amount DESC;

SQL Fiddle example