简体   繁体   中英

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. 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. Any suggestions on how to do this would be greatly appreciated.

You are grouping on the DateAndTime field, which contains also the time component. 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. Assuming this is SQL Server, I would write the query as something like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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