繁体   English   中英

SQL Server选择ID为ID的查询,ID计数按日期时间的转换日期分组

[英]Sql server select query of with ids, Count of ids grouped by casted date from datetime

我正在努力寻找一种正确的方法来编写选择查询,以产生具有唯一日期的ID计数,我将Log表设置为

id| DateTime
1|23-03-2019 18:27:45|
1|23-03-2019 18:27:45|
2|23-03-2019 18:27:50|
2|23-03-2019 18:27:51|
2|23-03-2019 18:28:01|
3|23-03-2019 18:33:15|
1|24-03-2019 18:13:18|
2|23-03-2019 18:27:12|
2|23-03-2019 15:27:46|
3|23-03-2019 18:21:58|
3|23-03-2019 18:21:58|
4|24-03-2019 10:11:14|

我尝试过的

select id, count(cast(DateTime as DATE)) as Counts from Logs group by id

其产生的ID的ID的正确计数

id|count
1 | 2|
2 | 3|
3 | 1|
1 | 1|
2 | 2|
3 | 2|
4 | 1|

我想要的是添加转换为日期的datetime列

id|count|Date
1 | 2| 23-03-2019
2 | 3| 23-03-2019
3 | 1| 23-03-2019
1 | 1| 24-03-2019
2 | 2| 24-03-2019
3 | 2| 24-03-2019
4 | 1| 24-03-2019

但是我得到一个错误的说法

Column 'Logs.DateTime' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

当我尝试

    select id, count(cast(DateTime as DATE)) as Counts from Logs group by id 

您还需要在分组依据中添加cast(DateTime as DATE)

select id,cast(DateTime as DATE) as dateval, count(cast(DateTime as DATE)) as Counts 
from Logs 
group by id,cast(DateTime as DATE)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM