有没有办法在不同的日期组合中使用查询,而无需单独更改每个组合的日期?
例如,而不是:
SELECT COUNT(X) FROM [TABLE]
WHERE date1 = '21-01-2017' and date2 = '22-01-2017'
SELECT COUNT(X) FROM [TABLE]
WHERE date1 = '22-01-2017' and date2 = '23-01-2017'
SELECT COUNT(X) FROM [TABLE]
WHERE date1 = '23-01-2017' and date2 = '24-01-2017'
输出:
23
7
25
所以,我想在一个查询中知道组合的输出:
date1 = '21-01-2017' and date2 = '22-01-2017'
date1 = '22-01-2017' and date2 = '23-01-2017'
date1 = '23-01-2017' and date2 = '24-01-2017'
在最理想的情况下,我不想手动更改每个日期,但有类似的内容:
的每个组合
((Date1 between '21-01-2017' and '23-01-2017') x
(Date2 between '22-01-2017' and '24-01-2017'))
答案 0 :(得分:1)
您可以对每个日期范围使用Case-When:
SELECT
COUNT ( CASE WHEN DATE1 BETWEEN '21-01-2017' AND '22-01-2017' then 1 ELSE NULL END) AS COL_21_01,
COUNT ( CASE WHEN DATE1 BETWEEN '22-01-2017' AND '23-01-2017' then 1 ELSE NULL END) AS COL_22_01
FROM [Table]
你会得到这样的:
COL_22_01 | COL_22_01
6 | 56