Get the latest records per Group By SQL

浪尽此生 提交于 2021-01-27 12:40:42

问题


I have the following table:

-----------------------------------------------------------
ID     oDate         oName     oItem    oQty    oRemarks
-----------------------------------------------------------
1      2016-01-01    A         001      2       
2      2016-01-01    A         002      1       test
3      2016-01-01    B         001      3  
4      2016-01-02    B         001      2
5      2016-01-02    C         001      2
6      2016-01-03    B         002      1
7      2016-01-03    B         001      4
       ff.

I want to get the latest record for each name. So the result should be like this:

-----------------------------------------------------------
oDate         oName     oItem    oQty    oRemarks
-----------------------------------------------------------
2016-01-01    A         001      2       
2016-01-01    A         002      1       test
2016-01-02    C         001      2
2016-01-03    B         002      1
2016-01-03    B         001      4
ff.

Does anyone know how to do get this result?
Thank you.


回答1:


The rank window clause allows you to, well, rank rows according to some partitioning, and then you could just select the top ones:

SELECT oDate, oName, oItem, oQty, oRemarks
FROM   (SELECT oDate, oName, oItem, oQty, oRemarks,
               RANK() OVER (PARTITION BY oName ORDER BY oDate DESC) AS rk
        FROM   my_table) t
WHERE  rk = 1



回答2:


This is a generic query without using analytical function.

SQLFiddle Demo

SELECT a.*
FROM table1 a
INNER JOIN
    (SELECT max(odate) modate,
          oname,
          oItem
   FROM table1
   GROUP BY oName,
            oItem
    ) 
    b ON a.oname=b.oname
AND a.oitem=b.oitem
AND a.odate=b.modate



回答3:


Add a primary key suppose id field to the table and make it auto increment,. Then order by id you will get it. It is the traditional way. By using your table you can only order by oDate. But is is having same date multiple times, so it also won't solve your problem.




回答4:


I think you need a query like this:

SELECT *
FROM (SELECT *,
        ROW_NUMBER() OVER (PARTITION BY oName ORDER BY oDate DESC) seq
    FROM yourTable) t
WHERE (seq <= 2)
ORDER BY oDate; 



回答5:


You have to use ROW_NUMBER in following:

select oDate, oName, oItem, oQty, oRemarks
from (
   select *, row_number() over(partition by oName, oItem order by oDate desc) rn  
   from #t
)x
where rn = 1
order by oDate

OUTPUT

oDate   oName   oItem   oQty    oRemarks    
2016-01-01  A   001     2                   
2016-01-01  A   002     1       test        
2016-01-02  C   001     2                   
2016-01-03  B   001     4                   
2016-01-03  B   002     1                   


来源:https://stackoverflow.com/questions/35219261/get-the-latest-records-per-group-by-sql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!