如何获得每个客户每天花费的最长时间

时间:2018-10-10 15:36:39

标签: sql

我想计算每天ID花费的最长时间

ID                  date    Time 
220B8DAAA53F35B 9/30/2018   16558
220B8DAAA53F35B 9/30/2018   22570
220B8DAAA53F35B 9/14/2018   6673
220B8DAAA53F35B 9/14/2018   2709
220B8DAAA53F35B 9/14/2018   19968
220B8DAAA53F35B 9/14/2018   2002
220B8DAAA53F35B 9/14/2018   6754
220B8DAAA53F35B 9/14/2018   6954
220B8DAAA53F35B 9/14/2018   16739
220B8DAAA53F35B 9/14/2018   8431
220B8DAAA53F35B 9/16/2018   16978
220B8DAAA53F35B 9/2/2018    21776
220B8DAAA53F35B 9/2/2018    14015
220B8DAAA53F35B 9/2/2018    294097
220B8DAAA53F35B 9/2/2018    543202
220B8DAAA53F35B 9/12/2018   18563
220B8DAAA53F35B 9/12/2018   17547

结果应该是

ID                  date    Time 
220B8DAAA53F35B 9/30/2018   16558
220B8DAAA53F35B 9/14/2018   19968
220B8DAAA53F35B 9/16/2018   16978
220B8DAAA53F35B 9/2/2018    543202
220B8DAAA53F35B 9/12/2018   18563

请帮助我写查询

谢谢

3 个答案:

答案 0 :(得分:1)

聚合是执行此操作的一种方法:

select id, date, max(time)
from table t
group by id, date;

答案 1 :(得分:1)

基本上,查询会为每个ID和日期值分组选择最大时间值

SELECT Max([Time])
       ,[Date]
       ,[ID]
FROM [YourTable]
GROUP BY [ID],[Date]

答案 2 :(得分:0)

经典行号

select top 1 with ties ID,date,time
from [your table]
order by row_number() over (partition by id,date order by time desc) 

我将在此处保留此答案供您查看,但其他选项可以满足您的高效需求。

但是,这是一种非常好的方法,可以将整行记录恢复为您要跟踪的记录。通常,您需要排除列才能获得所需的汇总。