CLOSE_DATE
字段IS NOT NULL
:
SELECT
YEAR (CLOSE_DATE) AS TheYear,
MONTH (CLOSE_DATE) AS TheMonth,
COUNT (*) AS cnt
FROM
Table1
WHERE
Table1.DEPT = 'SUPPORT'
GROUP BY
YEAR (CLOSE_DATE),
MONTH (CLOSE_DATE)
ORDER BY
TheYear DESC,
TheMonth DESC
输出结果为:
+-------------+------+
| Year | Month | cnt |
+-------------+------+
| 2014 | 4 | 10 |
| 2014 | 3 | 9 |
| 2014 | 2 | 15 |
| 2014 | 1 | 12 |
| 2013 | 12 | 10 |
| 2013 | 11 | 50 |
+--------------+-----+
如果CLOSE_DATE
有7行NULL
,则结果为:
+-------------+------+
| Year | Month | cnt |
+-------------+------+
| NULL | NULL | 7 |
| 2014 | 4 | 10 |
| 2014 | 3 | 9 |
| 2014 | 2 | 15 |
| 2014 | 1 | 12 |
| 2013 | 12 | 10 |
| 2013 | 11 | 50 |
+--------------+-----+
NULL
表示它应该计入实际年份和月份,因此预期结果应为:
+-------------+------+
| Year | Month | cnt |
+-------------+------+
| 2014 | 4 | 17 |
| 2014 | 3 | 9 |
| 2014 | 2 | 15 |
| 2014 | 1 | 12 |
| 2013 | 12 | 10 |
| 2013 | 11 | 50 |
+--------------+-----+
更新
上面的例子只是更大选择的一部分。我实际上是为了打开和关闭案件。
如果故障单没有close_date,则表示它已打开。因此,如果计算得很接近它应该算作开放。
选择相同,打开列:
SELECT
YEAR (OPEN_DATE) AS TheYear,
MONTH (OPEN_DATE) AS TheMonth,
COUNT (*) AS cnt
FROM
Table1
WHERE
Table1.DEPT = 'SUPPORT'
GROUP BY
YEAR (OPEN_DATE),
MONTH (OPEN_DATE)
ORDER BY
TheYear DESC,
TheMonth DESC
因此,行YEAR (OPEN_DATE) AS TheYear,
和MONTH (OPEN_DATE) AS TheMonth,
会带来open_date
列中的年份和月份,但是如果close_date
列is null
它应该依赖那条线也是。
这样,close_date
中包含空值的所有行都将被视为open_date
。
答案 0 :(得分:1)
您可以使用Isnull()
函数,只要null
值出现,此函数就会允许另一个预定义值。
SELECT
YEAR (Isnull(CLOSE_DATE,getdate())) AS TheYear,
MONTH (Isnull(CLOSE_DATE,getdate())) AS TheMonth,
COUNT (*) AS cnt
FROM
Table1
WHERE
Table1.DEPT = 'SUPPORT'
GROUP BY
YEAR (Isnull(CLOSE_DATE,getdate())),
MONTH (Isnull(CLOSE_DATE,getdate()))
ORDER BY
TheYear DESC,
TheMonth DESC