SQL to Count状态文本,并根据日期更改其中一些状态文本(及其计数)

时间:2016-04-15 00:11:17

标签: sql sql-server

花了一段时间寻找这个,但没有找到解决方案。问题:获取一列中状态值的计数。到目前为止非常简单,当DueDate(并且它可以为null)根据当前日期并且未完成时,我还想要更改/忽略其中的一些。还包括状态的空字符串。示例数据(原谅日期显示为文本...假设它是SQL日期类型 - 只是想让它更具可读性):

Current Date Apr : April 4, 2016

数据库表DispatchStatus

中的数据
Status        Due Date
=======================================
Complete      Mar 1, 2015                  <-- would not be Late since Complete
Complete      null
Complete      July 12, 2016
Complete      July 16, 2016
Started       Mar 3, 2017
Started       null
Started       Feb 9, 2015                   <-- Late
OnDevice      June, 2016
OnDevice      Dec 3, 2015                   <-- Late
Dispatched    Nov 16, 2015                  <-- Late
Dispatched    null
Dispatched    Nov 20, 2016
              Nov 15, 2017
              null
              Jan 15, 2016                  <-- Late

查询应返回:

Status        Count
=========================
Complete        4
Started         2
OnDevice        1
                2
Dispatched      2
Late            4   

谢谢!

1 个答案:

答案 0 :(得分:2)

CASE表达式与COUNT一起使用:

DECLARE @currentDate DATE = '20160404'

SELECT
    Status =
        CASE 
            WHEN DueDate <= @currentDate AND ISNULL(Status, '') <> 'Complete' THEN 'Late'
            ELSE Status
        END,
    COUNT(*)
FROM DispatchStatus
GROUP BY
    CASE 
        WHEN DueDate <= @currentDate AND ISNULL(Status, '') <> 'Complete' THEN 'Late'
        ELSE Status
    END

我认为根据您的示例输出,您的样本当前日期应为Apr 4, 2016