2015-09-21 193 views
0

我是新來的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; 
+0

謝謝,問題是我有這種情況在哪裏,它應該在選擇。我也通過固定小組。它的工作原理罰款如下: – sqljeopardy

+0

選擇 DEPT_C AS 「部門代碼」, (CASE WHEN DEPT_C = 'D01',然後 'WOMAN ACTIVE WEAR' WHEN DEPT_C = 'D02',然後 'WOMAN PLUS SIZE' WHEN DEPT_C =' D03' THEN 'JUNIORS' WHEN DEPT_C = 'D04' THEN 'GIRLS' WHEN DEPT_C = 'D05' THEN '嬰兒和學步兒童' WHEN DEPT_C = 'D06' THEN '附件' WHEN DEPT_C = 'D07' THEN'條我們」 WHEN DEPT_C = 'D08' THEN '香水' WHEN DEPT_C = 'D09' THEN 'COSMETICS' ELSE '其他' END)DEPT_NAME, TO_CHAR(COUNT(*), '999999999999')爲總 FROM STORE .DEPT GROUP BY DEPT_C ORDER BY 2,1; – sqljeopardy

回答

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