SQL在单选语句中将列转换为行

时间:2014-03-13 06:57:40

标签: sql sql-server sql-server-2008 calculated-columns

我需要转换SQL输出的解决方案

我正在写

    SELECT Merchant_Master.Merchant_ID,
           COUNT(Coupon_Type_ID) AS "Total Coupons",
           Coupon_Type_ID,
           CASE WHEN Coupon_Type_ID=1 
                     THEN COUNT(Coupon_Type_ID)
            END AS "Secret",
           CASE WHEN Coupon_Type_ID=2 
                     THEN count(Coupon_Type_ID)
            END AS "Hot"
      FROM Coupon_Master 
           INNER JOIN Merchant_Master 
               ON Coupon_Master.Merchant_ID=Merchant_Master.Merchant_ID
    GROUP BY 
           Coupon_Master.Coupon_Type_ID,
           Merchant_Master.Merchant_ID

将输出设为

Merchant_ID Total Coupons Coupon_Type_ID Secret      Hot
----------- ------------- -------------- ----------- -----------
20          6             1              6           NULL
22          4             1              4           NULL
22          2             2              NULL        2
23          1             2              NULL        1
24          2             1              2           NULL
25          3             1              3           NULL
25          2             2              NULL        2

但我希望输出为

Merchant_ID     Secret     Hot_Coupons     
-----------     ------    ------------- 
20                6             0
22                4             2
23                0             1
24                2             0
25                3             2

请帮我解决问题。

2 个答案:

答案 0 :(得分:2)

CASE表达式移到聚合中。我也转而使用SUM而不是COUNT - 有一个COUNT变体,但它可能会显示有关消除我宁愿避免的NULL值的警告。

SELECT Merchant_Master.Merchant_ID,
       SUM(CASE WHEN Coupon_Type_ID=1 
                 THEN 1 ELSE 0 END) AS "Secret",
       SUM(CASE WHEN Coupon_Type_ID=2 
                 THEN 1 ELSE 0 END) AS "Hot"
  FROM Coupon_Master 
       INNER JOIN Merchant_Master 
           ON Coupon_Master.Merchant_ID=Merchant_Master.Merchant_ID
GROUP BY 
       Merchant_Master.Merchant_ID

答案 1 :(得分:0)

将其放在子查询中并添加group by Merchant_ID, Total, Coupons, Coupon_Type_ID

聚合秘密,热门为SUM

select 
...
SUM(secret) as secret,
SUM(Hot_Coupons) as Hot_Coupons     
FROM (your original query) raw
group by Merchant_ID, Total, Coupons, Coupon_Type_ID