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

时间:2019-03-29 05:56:03

标签: sql sql-server tsql

我正在努力寻找一种正确的方法来编写选择查询,该查询会生成具有唯一日期的ID计数,我的日志表为

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|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 

1 个答案:

答案 0 :(得分:3)

您还需要在分组依据中添加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)