sql-server:重写此查询以使值成为列

时间:2014-06-17 16:50:27

标签: sql-server

下面的查询为每列GER1,2和3分配权重。增加生长,效率和风险发生的次数。 http://i.imgur.com/zGFGMNF.png

如何将其重写为显示相同结果的位置,但“增长”,“效率”和“风险”是以score为值的列名称。无需显示rank

期望的输出:

Growth    Efficiency   Risk

8            15          7 

-

 declare @MainHospital varchar(50)='Hospital1';
                                   WITH cte AS (
                                   SELECT 2 score, GER1 area FROM Survey
                                   WHERE MainHospital = @MainHospital
                                   UNION ALL
                                   SELECT 1 score, GER2 area FROM Survey
                                   WHERE MainHospital = @MainHospital
                                   UNION ALL
                                   SELECT 0 score, GER3 area FROM Survey
                                   WHERE MainHospital = @MainHospital
                                   ), cte2 AS (
                                   SELECT area, SUM(score) score FROM cte
                                   GROUP BY area
                                   HAVING area IS NOT NULL


                                   ), cte3 AS (
                                   SELECT area, score, 
                                   RANK() OVER (ORDER BY score DESC) rank
                                   FROM cte2
                                   )
                                   SELECT rank, area, score
                                   FROM cte3
                                   ORDER BY rank;

取消提供的答案,我该如何压缩此查询

SELECT    
   SUM(CASE WHEN [GER1] = 'Growth' THEN 2 ELSE 0 END) as "Growth",
   SUM(CASE WHEN [GER1] = 'Efficiency' THEN 2 ELSE 0 END) as Efficiency,
   SUM(CASE WHEN [GER1] = 'Risk' THEN 2 ELSE 0 END) as Risk,

   SUM(CASE WHEN [GER2] = 'Growth' THEN 1 ELSE 0 END) as "Growth",
   SUM(CASE WHEN [GER2] = 'Efficiency' THEN 1 ELSE 0 END) as Efficiency,
   SUM(CASE WHEN [GER2] = 'Risk' THEN 1 ELSE 0 END) as Risk,

   SUM(CASE WHEN [GER3] = 'Growth' THEN 0 ELSE 0 END) as "Growth",
   SUM(CASE WHEN [GER3] = 'Efficiency' THEN 0 ELSE 0 END) as Efficiency,
   SUM(CASE WHEN [GER3] = 'Risk' THEN 0 ELSE 0 END) as Risk,


FROM Survey
WHERE MainHospital = @MainHospital
GROUP BY MainHospital;

1 个答案:

答案 0 :(得分:1)

对于固定数量的列,我只会使用case语句,类似于以下几行:

...
sum (case when area='Efficiency' then score else 0 end) as Efficiency,
...

你可以看一下旋转,但我认为这更简单。

编辑: 我不确定我完全理解一切。但我认为你不需要那么多案例陈述。我想你可以这样做:

sum (case 
  when [GER1] = 'Growth' then 2
  when [GER2] = 'Growth' then 1
  when [GER3] = 'Growth' then 0  -- If it's really 0 you could just leave this one out
  else 0 
end) as "Growth"...