[英]Trying to get the count of items per day with SQL query
I have a db with several days of data and I want to get the count of each record with Status=0, Status=1...Status=8 for each day. 我有一个数据库,其中包含几天的数据,我想每天获取状态为Status = 0,Status = 1 ... Status = 8的每个记录的计数。 I was to see something like.
我当时正看到类似的东西。
DateAndTime State_0 State_1 State_2
2014-08-15 5 8 9
2014-08-16 2 5 6
2014-08-17 4 2 3
I was trying this: 我正在尝试这个:
SELECT DISTINCT DATEADD(dd,(DATEDIFF(dd,0,DateAndTime)),0) AS DateAndTime,
SUM( Case When State=0 Then 1 Else 0 End) AS State_0,
SUM( Case When State=1 Then 1 Else 0 End) AS State_1,
SUM( Case When State=2 Then 1 Else 0 End) AS State_2
FROM [DB_002].[dbo].[MyDb]
Group By DateAndTime
Order by DateAndTime
But it keeps adding rows for each state that I add. 但它会继续为我添加的每个状态添加行。 That is with 3 states I'm getting 4 rows for each date.
在3个状态下,每个日期我都会得到4行。 Any suggestions on how to do this would be greatly appreciated.
任何有关如何执行此操作的建议将不胜感激。
You are grouping on the DateAndTime
field, which contains also the time component. 您正在对
DateAndTime
字段进行分组,该字段还包含时间分量。 That makes each record practically unique, so there will be a single record in each group. 这使得每个记录实际上都是唯一的,因此每个组中将只有一个记录。
Group on the date only: 仅在日期分组:
Group By DATEADD(dd,(DATEDIFF(dd,0,DateAndTime)),0)
Order by DATEADD(dd,(DATEDIFF(dd,0,DateAndTime)),0)
You are confused because you have changed a column and given it the same name as the original column. 您很困惑,因为您已更改了列并为其指定了与原始列相同的名称。 When you say
group by DateAndTime
, that is referring to the column in the table. 当您说“
group by DateAndTime
,是指表中的列。 Assuming this is SQL Server, I would write the query as something like this: 假设这是SQL Server,我将查询编写为如下形式:
SELECT cast(d.DateAndTime as Date) as DateAndNoTime,
SUM(Case When d.State = 0 Then 1 Else 0 End) AS State_0,
SUM(Case When d.State = 1 Then 1 Else 0 End) AS State_1,
SUM(Case When d.State = 2 Then 1 Else 0 End) AS State_2
FROM [DB_002].[dbo].[MyDb] d
Group By cast(d.DateAndTime as Date)
Order by DateAndNoTime;
This changes the name of the alias in the select
to avoid confusion. 这将更改
select
别名的名称,以避免混淆。 It uses the alias for column references, to also clarify the meaning of the query. 它使用别名作为列引用,以阐明查询的含义。 And, it uses
cast()
instead of the old datedd
/ datediff
trick. 并且,它使用
cast()
代替了旧的datedd
/ datediff
技巧。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.