如何选择按一列分组的多列

时间:2019-03-29 09:41:45

标签: sql sql-server select

我有..

Date         ID   Qty  
2019/5/1     A    11  
2019/6/1     A    22 
2019/7/1     B    33  
2019/6/1     B    44  

我需要如下所示的每个ID的最大日期的ID和数量数据

Date         ID   Qty  
2019/6/1     A    22
2019/7/1     B    33

我用..

select max(Date),ID,Qty from table group by ID,Qty  

但是结果不是我期望的

4 个答案:

答案 0 :(得分:2)

group by可能不是适合该工作的工具。相反,您可以使用rank查找每个组的第一行,并根据其进行过滤:

SELECT date, id, qty
FROM   (SELECT date, id, qty, RANK() OVER (PARTITION BY id ORDER BY date DESC) AS rk
        FROM   mytable) t
WHERE  rk = 1

答案 1 :(得分:1)

您可以使用以下解决方案:

SELECT t.* 
FROM table_name t INNER JOIN (
    SELECT MAX(Date) AS Date, ID 
    FROM table_name
    GROUP BY ID
) tMAX ON t.ID = tMAX.ID AND t.Date = tMAX.Date

demo on dbfiddle.uk

答案 2 :(得分:1)

尝试一下

SELECT Date,
       ID,
       Qty 
FROM
(
SELECT Date,
       ROW_NUMBER()OVER(PARTITION BY ID ORDER BY Date DESC) AS Grp,
       ID,
       Qty 
FROM <Table>
)Dt
WHERE Dt.Grp = 1

答案 3 :(得分:0)

您可以使用相关子查询

select t1.* from table_name t1
where date=( select max(date) from table_name t2 where t2.id=t1.id)