SQL查询以获取最大值';s数据与分组方式
我有下表:SQL查询以获取最大值';s数据与分组方式,sql,sql-server,tsql,Sql,Sql Server,Tsql,我有下表: Date Id Count 2018-09-01 100 50 2018-09-01 101 60 2018-09-01 102 55 2018-09-02 103 40 2018-09-02 104 30 2018-09-02 105 20 2018-09-02 106 10 2018-09-03 107 30 2018-09-03 108 70 我想得到每个日期都有max Id的
Date Id Count
2018-09-01 100 50
2018-09-01 101 60
2018-09-01 102 55
2018-09-02 103 40
2018-09-02 104 30
2018-09-02 105 20
2018-09-02 106 10
2018-09-03 107 30
2018-09-03 108 70
我想得到每个日期都有max Id的行及其max Id的count列
结果表:
Date Id Count
2018-09-01 102 55
2018-09-02 106 10
2018-09-03 108 70
要得到这个结果,sql查询应该是什么
谢谢。您不需要聚合,而是需要筛选
select t.*
from t
where t.count = (select max(t2.count) form t t2 where t2.date = t.date);
使用行编号()
:
我认为使用自联接是一种替代方法:
select t.*
from table t
inner join (select Date, max(t.ID) as DID from table t group by Date) t2
on t.Date = t2.Date and t.ID = t2.DID
我喜欢with ties的内联,但注意到它的性能比CTE或派生表中的窗口函数差。你看到这个了吗?
select t.*
from table t
inner join (select Date, max(t.ID) as DID from table t group by Date) t2
on t.Date = t2.Date and t.ID = t2.DID