简体   繁体   English

每天的SQL计数状态

[英]SQL Count Status For Each Day

Fairly new to SQL, but I am looking for help with organizing some data. 对于SQL来说还算是新手,但我正在寻求有关组织某些数据的帮助。 Have several status broken out into different columns with date/time and want to be able to pivot them to give a breakdown of the different status on each day. 将几个状态细分为不同的日期/时间列,并希望能够对其进行透视以提供每天不同状态的细分。

For instance the following data: 例如以下数据:

 Status4            Status5             Status6             Status7
 12/1/17 5:46       NULL                NULL                NULL
 11/30/17 14:53     11/30/17 14:53      11/30/17 14:53      11/30/17 14:54
 11/18/17 4:50      11/18/17 4:48       11/18/17 4:48       NULL    

Would return a table such as the one below with the bounds of highest and lowest date present in Status4. 将返回一个表格,例如下面的表格,其中包含Status4中最高日期和最低日期的界限。

               Status4      Status5     Status6     Status7
 11/18/17          1           1           1        0
 11/30/17          2           2           2        1
 12/1/1            3           2           2        1

Thanks! 谢谢!

If you are looking at getting counts against each date, try this code. 如果要查看每个日期的计数,请尝试以下代码。
Please note you have to write a dynamic query, if number of status columns is dynamic / unknown. 请注意,如果状态列数为动态/未知,则必须编写动态查询。

DECLARE @TempDates As Table (DateValues Date)

/*Table1 is the table having your status columns */
Insert into @TempDates
    Select Convert(Date,Status1) from Table1
    Union 
    Select Convert(Date,Status2) from Table1
    Union 
    Select Convert(Date,Status3) from Table1
    Union
    Select Convert(Date,Status4) from Table1

    SELECT * FROM 
             (
                 SELECT COL, VAL, DateValues FROM Table1
                 CROSS APPLY (VALUES (Convert(Date,Status1),'Status1'),
                                      (Convert(Date,Status2),'Status2'),
                                      (Convert(Date,Status3),'Status3'),
                                      (Convert(Date,Status4),'Status4')) CS (COL,VAL)
                RIGHT JOIN @TempDates tp ON tp.DateValues = CS.COL
            )T
            PIVOT 
            ( 
                    COUNT(COL)
                    FOR VAL in ([Status1],[Status2],[Status3],[Status4])
            ) P
            WHERE Datevalues IS NOT NULL

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

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