Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
SQL查询以获取最大值';s数据与分组方式_Sql_Sql Server_Tsql - Fatal编程技术网

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