SQL Case - ELSE返回的分组值

时间:2018-06-13 12:38:05

标签: sql

This is my case expression:

These are my results:

如何只为“其他”类别收到一行,总共111?

2 个答案:

答案 0 :(得分:1)

您应该使用GROUP BY CASE表达式代替HHHOGCL

SELECT CASE hhhogcl
                  WHEN 'P' THEN 'One Step'
                  WHEN 'O' THEN 'Customer Service'
                  WHEN 'R' THEN 'Remote FTP'
                  WHEN 'N' THEN 'PowerNet'
                  WHEN 'S' THEN 'PowerSell'
                  WHEN 'M' THEN 'PowerMobile'
                  ELSE 'Other'
         END            AS "Channel",
         Count(*) AS "Orders per Channel"
FROM     s2151bdw.pwrdta.ffdcstbp
JOIN     s2151bdw.pwrdta.hhhordhl0
ON       hhhcusn = ffdcusn
WHERE    hhhcmpn = 1
AND      hhhdivn = 1
AND      hhhdptn = 1
AND      hhhdtes > 0 --Ship Date AND HHHDTES BETWEEN 20180611 AND 20180611
GROUP BY
         CASE hhhogcl
                  WHEN 'P' THEN 'One Step'
                  WHEN 'O' THEN 'Customer Service'
                  WHEN 'R' THEN 'Remote FTP'
                  WHEN 'N' THEN 'PowerNet'
                  WHEN 'S' THEN 'PowerSell'
                  WHEN 'M' THEN 'PowerMobile'
                  ELSE 'Other'
         END 

答案 1 :(得分:1)

CASE查询包含在派生表中,GROUP BY结果。

select "Channel", count(*) AS "Orders per Channel"
from
(
    SELECT CASE hhhogcl
                      WHEN 'P' THEN 'One Step'
                      WHEN 'O' THEN 'Customer Service'
                      WHEN 'R' THEN 'Remote FTP'
                      WHEN 'N' THEN 'PowerNet'
                      WHEN 'S' THEN 'PowerSell'
                      WHEN 'M' THEN 'PowerMobile'
                      ELSE 'Other'
             END            AS "Channel",
    FROM     s2151bdw.pwrdta.ffdcstbp
    JOIN     s2151bdw.pwrdta.hhhordhl0
    ON       hhhcusn = ffdcusn
    WHERE    hhhcmpn = 1
    AND      hhhdivn = 1
    AND      hhhdptn = 1
    AND      hhhdtes > 0 --Ship Date AND HHHDTES BETWEEN 20180611 AND 20180611
) dt
GROUP BY "Channel"

ANSI SQL兼容!