我有以下数据
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是这样的..
ID Stat CDate
2 1 2009-06-20
4 2 2009-06-10
我已尝试使用以下查询但未成功,请建议。
Select Distinct stat,MAX(Cdate) dt,id From testtable
Group By stat,id
得到解决方案..
从testtableas F1中选择f1.id,f1.stat,f1.cdate 加入(选择stat,MAX(cdate)作为来自testtable group by stat的dt)为F2 在f2.stat = F1.stat和f2.dt = f1.cdate
答案 0 :(得分:4)
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
答案 1 :(得分:2)
我假设你想要属于最大日期的属性,对吗?
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
答案 2 :(得分:1)
您无法在此处添加ID。因为对id的分组将不会是期望的结果。 id默认情况下是不同的。所以对id进行分组会产生所有数据。
答案 3 :(得分:1)
;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
答案 4 :(得分:1)
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;
内部查询的输出如下:
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
执行完整查询后的输出:
ID Stat Date
2 1 2009-06-20
4 2 2009-06-10
希望这会有所帮助。再见。