2015-01-08 79 views
1

我試圖在一個表中獲取兩個單獨列的數據。通過同一分組計算2列

我有一個跟蹤問題的數據庫,一個問題表有兩個相關的列,每個列都包含一個日期。非常類似於以下內容。

DateOpened DateClosed 
2015-01-08 2015-01-08 
2015-01-08 2015-01-08 
2015-01-06 2015-01-08 
2015-01-06 2015-01-08 
2015-01-04 2015-01-07 
2015-01-02 2015-01-07 
2015-01-02 2015-01-07 

我的目標是能夠計算每個日期打開和關閉的條目數。上述預期產出的一個例子是。

Date   CountDateOpened CountDateClosed 
2015-01-08 2    4 
2015-01-07 0    3 
2015-01-06 2    0 
2015-01-05 0    0 
2015-01-04 1    0 
2015-01-03 0    0 
2015-01-02 2    0 

我知道我需要按日期,但應該有天,其中更多的問題比開閉,但我COUNT(DateClosed)似乎從來沒有超過我的伯爵(DateOpened)。我正在處理查詢中的飛行日期轉換,但我不相信它們是相關的,因爲我總是輪到最近的一天。以下是我目前運行的查詢,爲簡單起見而剝皮。

SELECT 
    CREATEDATE AS [Date], 
    COUNT(CREATEDATE) AS [Number Opened], 
    COUNT(CLOSEDATE) AS [Number Closed] 

FROM 
    ISSUE 

GROUP BY 
    CREATEDATE 

ORDER BY 
    [Date] DESC 

回答

3

這樣做的一種方法是使用union all創建兩個日期,然後根據其類型組一列:

SELECT `Date`, 
     COUNT(`open`) AS `CountDateOpened` 
     COUNT(`closed`) AS `CountDateClosed` 
FROM  (SELECT `DateOpened` AS `Date`, 1 AS `open`, NULL AS `closed` 
      FROM `issue` 
      UNION ALL 
      SELECT `DateClosed` AS `Date`, NULL AS `open`, 1 AS `closed` 
      FROM `issue` 
     ) t 
GROUP BY `Date` 
ORDER BY `Date` DESC 
+0

精解。只需要「ORDER BY date DESC」 – twyly

+0

@twylyc錯過了OP的查詢中的'order by' - 編輯和添加。感謝您指出! – Mureinik

+1

這將不會在輸出中包含「2015-01-05」和「2015-01-03」,因爲它不存在於表 –

1

試試這個

select 
d.dt,(select COUNT(DateOpened) ct from ISSUE where 
CAST(DateOpened as DATE)=CAST(d.dt as DATE)) 
,(select COUNT(DateClosed) ct from ISSUE where 
CAST(DateClosed as DATE)=CAST(d.dt as DATE)) 
from (
select number,DATEADD(D,number-7,GETDATE()) dt 
from master.dbo.spt_values sp 
where type='P' and DATEADD(D,number-7,GETDATE())<'2015-01-09' 
) 
d 
ORDER BY d.dt desc 

OUTPUT

Date  DateOpened DateClosed 
2015-01-08 2   4 
2015-01-07 0   3 
2015-01-06 2   0 
2015-01-05 0   0 
2015-01-04 1   0 
2015-01-03 0   0 
2015-01-02 2   0 
+0

中,這非常麻煩。看到工會的想法。 – Strawberry

+0

@Strawberry是的......但他應該使用數字表,否則它會錯過'2015-01-05'和'2015-01-03' –

0

同Mureinik的回答,只是少一點打字...

SELECT date,SUM(status='opened') opened, SUM(status = 'closed') closed 
    FROM 
    (SELECT dateopened date,'opened' status FROM my_table 
     UNION ALL 
     SELECT dateclosed,'closed' FROM my_table 
    ) x 
GROUP 
    BY date DESC;