2013-07-04 110 views
5

我正在嘗試做一些非常類似於之前詢問過的問題,但我似乎無法使其正常工作。這是我剛纔的問題:How to get totals per dayMSSQL每天總計一個月

表如下所示:

   Table Name: Totals 
Date  |Program label |count 
      |    |  
2013-04-09 |Salary Day  |4364 
2013-04-09 |Monthly   |6231 
2013-04-09 |Policy   |3523 
2013-04-09 |Worst Record |1423 
2013-04-10 |Salary Day  |9872 
2013-04-10 |Monthly   |6543 
2013-04-10 |Policy   |5324 
2013-04-10 |Worst Record |5432 
2013-04-10 |Salary Day  |1245 
2013-04-10 |Monthly   |6345 
2013-04-10 |Policy   |5431 
2013-04-10 |Worst Record |5232 

我的問題是:使用MSSQL 2008 - 有我得到每程序標籤的總計數,每天的一種方式這個月。正如你可以看到有時它會每天運行兩次。我需要能夠解釋這一點。

輸出應如下所示:

Date  |Salary Day |Monthly |Policy |Worst Record 
2013-04-9 |23456  |63241 |23521 |23524 
2013-04-10|45321  |72535 |12435 |83612 

回答

3

試試這個

select Date, 
    sum(case when [Program label] = 'Salary Day' then count else 0 end) [Salary Day], 
    sum(case when [Program label] = 'Monthly' then count else 0 end) [Monthly], 
    sum(case when [Program label] = 'Policy' then count else 0 end) [Policy], 
    sum(case when [Program label] = 'Worst Record' then count else 0 end) [Worst Record] 
from Totals Group by [Date]; 
+0

我已經使用了您的答案,因爲它是最簡單的,對我來說,儘管我不得不編輯它很多。謝謝。 :) – DeanMWake

8

使用PIVOT表操作是這樣的:

SELECT * 
FROM Totals AS t 
PIVOT 
(
    SUM(count) 
    FOR [Program label] IN ([Salary Day], 
          [Monthly], 
          [Policy], 
          [Worst Record]) 
) AS p; 

看到它在行動:

這會給你:

|  DATE | SALARY DAY | MONTHLY | POLICY | WORST RECORD | 
------------------------------------------------------------- 
| 2013-04-09 |  4364 | 6231 | 3523 |   1423 | 
| 2013-04-10 |  11117 | 12888 | 10755 |  10664 | 
+0

感謝。我通過這個學到了新的東西:)真正有用的答案。我還沒有選擇使用它,因爲它不是我完全適應的東西。雖然我肯定會開始對我未來的疑問進行測試。 – DeanMWake

+0

@MethodMan - 隨時歡迎您,很高興我可以幫助:) –

2

嘗試這一個 -

SELECT 
    date 
    , [Salary Day] = SUM(CASE when [Program label] = 'Salary Day' then COUNT end) 
    , [Monthly] = SUM(CASE when [Program label] = 'Monthly' then COUNT end) 
    , [Policy] = SUM(CASE when [Program label] = 'Policy' then COUNT end) 
    , [Worst Record] = SUM(CASE when [Program label] = 'Worst Record' then COUNT end) 
FROM Totals 
GROUP BY [Date];