花了一段时间寻找这个,但没有找到解决方案。问题:获取一列中状态值的计数。到目前为止非常简单,当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
谢谢!
答案 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
。