在Where子句中的案例

时间:2015-09-21 16:26:45

标签: sql case where

我是SQL的新手,我正在尝试理解CASE子句。我想在计算商品时在部门代码旁边的报告中打印部门名称。你能告诉我我做错了吗?谢谢。

SELECT  
DEPT_C AS "DEPT CODE",
NAME as "DEPT NAME",
TO_CHAR(COUNT(*), '999,999,999,999') AS TOTAL 
FROM STORE.DEPT 
WHERE CASE  
WHEN DEPT_C = 'D01' THEN 'WOMAN ACTIVE WEAR' 
WHEN DEPT_C = 'D02' THEN 'WOMAN PLUS SIZE'
WHEN DEPT_C = 'D03' THEN 'JUNIORS'
WHEN DEPT_C = 'D04' THEN 'GIRLS'
WHEN DEPT_C = 'D05' THEN 'INFANTS AND TODDLERS'
WHEN DEPT_C = 'D06' THEN 'ACCESSORIES'
WHEN DEPT_C = 'D07' THEN 'JEWLERY'
WHEN DEPT_C = 'D08' THEN 'PERFUME'
WHEN DEPT_C = 'D09' THEN 'COSMETICS'
ELSE 'OTHER' END NAME
GROUP BY 1,2
ORDER BY 2,1;

1 个答案:

答案 0 :(得分:3)

CASE视为switch声明。

在这种情况下,您需要为每个部门代码使用不同的名称。因此,您的案例使用DEPT_C列作为参考变量,并为各个代码指定名称值。

像这样:

SELECT  
DEPT_C AS "DEPT CODE",
CASE DEPT_C
WHEN 'D01' THEN 'WOMAN ACTIVE WEAR' 
WHEN 'D02' THEN 'WOMAN PLUS SIZE'
WHEN 'D03' THEN 'JUNIORS'
WHEN 'D04' THEN 'GIRLS'
WHEN 'D05' THEN 'INFANTS AND TODDLERS'
WHEN 'D06' THEN 'ACCESSORIES'
WHEN 'D07' THEN 'JEWLERY'
WHEN 'D08' THEN 'PERFUME'
WHEN 'D09' THEN 'COSMETICS'
ELSE 'OTHER' 
END as 'DEPT NAME'
FROM STORE.DEPT 

修改

您也可以忽略input expression,即DEPT_C,但每个条件都应该是明确的,如下所示:

SELECT  
DEPT_C AS "DEPT CODE",
CASE 
WHEN DEPT_C = 'D01' THEN 'WOMAN ACTIVE WEAR' 
WHEN DEPT_C = 'D02' THEN 'WOMAN PLUS SIZE'
WHEN DEPT_C = 'D03' THEN 'JUNIORS'
WHEN DEPT_C = 'D04' THEN 'GIRLS'
WHEN DEPT_C = 'D05' THEN 'INFANTS AND TODDLERS'
WHEN DEPT_C = 'D06' THEN 'ACCESSORIES'
WHEN DEPT_C = 'D07' THEN 'JEWLERY'
WHEN DEPT_C = 'D08' THEN 'PERFUME'
WHEN DEPT_C = 'D09' THEN 'COSMETICS'
ELSE 'OTHER' 
END as 'DEPT NAME'
FROM STORE.DEPT 

<强> CAVEAT: 我更改了您的选择顺序,请务必相应地重写GROUP BYORDER BY