2017-06-21 79 views
0

有沒有辦法在不同的日期組合上使用查詢,而無需分別更改每個組合的日期?多個日期(獨立)的輸出


例如,而不是:

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' 

OUTPUT:

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')) 
+1

嗯,你說的!你可以使用'BETWEEN'! –

+0

@HamzaAbdaoui不會給出另一個輸出,即: 不是23 7 25,而是55? 目標是看到日期的最小值,所以我希望這個日期範圍給出7,但我所做的所有嘗試的結果是55或25.第一步是要知道每一天的價值。 –

+0

好點!您是否嘗試過'21 -01-2017'和'23 -01-2017'之間的'GROUP BY date1 HAVING Date1'和'22 -01-2017'和'24 -01-2017''之間的Date2,類似這樣的.. –

回答

1

您可以使用各種組合情況,當每個範圍日期:

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] 

,你會得到這樣的:

CO L_22_01 | COL_22_01

6 | 56