2014-02-20 52 views
1

我寫了下面的腳本,但不幸的是已經卡住了。 目前,它讀取將行合併爲1併合計金額

SELECT dim1  AS Costc, 
     period  AS Period, 
     sum(actual) AS Beds, 
     CASE 
     WHEN measure LIKE 'beds%' THEN ISNULL(sum(actual), 0) 
     END   AS BEDS, 
     CASE 
     WHEN measure LIKE 'occu%' THEN ISNULL (sum(actual), 0) 
     END   AS OCCU, 
     measure 
FROM statistics 
WHERE measure IN (SELECT measure 
        FROM statistics 
        WHERE measure LIKE 'beds%' 
          OR measure LIKE 'occu%') 
     AND dim1 = 'ABC' 
     AND period = '201301' 
GROUP BY period, 
      dim1, 
      measure 

這 回報

COSTC | Period | Beds | BEDS | OCCU | Measure 
ABC | 201301 | 40 | 40 | NULL | beds_abc 
ABC | 201301 | 35 | 35 | NULL | beds_def 
ABC | 201301 | 30 | NULL | 30 | occu_abc 
ABC | 201301 | 20 | NULL | 20 | occu_def 

我期望的輸出是

COSTC | Period | BEDS | OCCU 
ABC | 201301 | 75 | 50 

任何幫助,將不勝感激 感謝

+0

您正在使用哪個數據庫管理系統外的集合體? –

回答

1

這應該這樣做。

取下GROUP BYmeasure,你需要移動CASE表達

SELECT dim1    AS Costc, 
     period    AS Period, 
     sum(actual)   AS Beds, 
     isnull(SUM(CASE 
        WHEN measure LIKE 'beds%' THEN actual 
        END), 0) AS BEDS, 
     isnull(SUM(CASE 
        WHEN measure LIKE 'occu%' THEN actual 
        END), 0) AS OCCU 
FROM statistics 
WHERE measure IN (SELECT measure 
        FROM cukstats 
        WHERE measure LIKE 'beds%' 
          OR measure LIKE 'occu%') 
     AND dim1 = 'ABC' 
     AND period = '201301' 
GROUP BY period, 
      dim1 
+0

如果「度量」不屬於組的一部分,則「度量」不能位於選擇列表中。 – bleeeah

+0

@bleeeah - 它不在'SELECT'列表中。它在一個聚合中。這是一種普通的「PIVOT」方法。 –

+0

是的,這對BEDS和OCCU來說很好,但它仍然是最後一列被返回。 – bleeeah