Group by with 2 distinct columns in SQL Server

混江龙づ霸主 提交于 2020-01-03 19:07:08

问题


I have data like below

ID  Stat    Date
1   1       2009-06-01
2   1       2009-06-20
3   1       2009-06-10
4   2       2009-06-10

O/P to be like this..

ID     Stat   CDate
2      1      2009-06-20
4      2      2009-06-10

I have tried with below query and was unsuccessful, please suggest.

Select Distinct stat,MAX(Cdate) dt,id  From testtable
Group By stat,id

Got the solution..

Select f1.id,f1.stat,f1.cdate From testtableas F1 Join(Select stat,MAX(cdate) as dt from testtable group by stat) as F2 On f2.stat=F1.stat and f2.dt=f1.cdate


回答1:


SELECT t1.id, t1.stat, t1.date
FROM testtable t1
JOIN (SELECT stat, MAX(date) date FROM testtable GROUP BY stat) t2 ON t1.stat = t2.stat AND t1.date = t2.date
GROUP BY stat



回答2:


I'm assuming you want the stat belonging to the maximum date, right?

select t1.id, t1.stat, t1.cdate 
from testtable t1,
  (select stat, max(cdate) max_date from testtable
   group by stat) t2
where t1.stat = t2.stat and t1.cdate = t2.max_date



回答3:


You cannot add the id here. Because grouping on id will result will not be the desired result. id is distinct in its nature by default. so grouping on id will result all the data.




回答4:



;with CTE AS
(
    Select stat,MAX(Cdate)Over(Partition by stat) as dt,id
    From testtable  
)
Select ID,stat,dt
From CTE
Inner JOIn testtable On testtable.id=CTE.ID and testtable.date=CTE.dt
Group By stat




回答5:


I liked the solution by nicktrs, though. If you are using SQL SERVER 2005 or later, this might work for you;

select k.id, k.stat, k.cdate from(
    select id, stat, cdate, row_num=rownumber()
    over (partition by stat order by cdate desc) as k from testtab )
where k.row_num=1;

output of inner query goes like this:

ID  Stat    Date         Row_num
2   1       2009-06-20   1
3   1       2009-06-10   2
1   1       2009-06-01   3
4   2       2009-06-10   1

Output after full query is executed:

ID  Stat    Date
2   1       2009-06-20
4   2       2009-06-10

Hope this helps. Adieu.



来源:https://stackoverflow.com/questions/6594536/group-by-with-2-distinct-columns-in-sql-server

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