2014-02-20 55 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