[英]Getting Null values when using Case statement
我正在嘗試根據另一列( Selection
和IsAssetCode
)派生一列( Level5
)。
Selection
列有兩種類型的條目 - “所有資產”和“核心資產”,並且IsAssetCode
是0
或1
。 IsAssetCode = 0
對應“所有資產”, 1
是“核心資產”。
我試圖將核心資產和非核心資產分開,但我在Level5
獲得了帶有“所有資產”的額外行。
Select *,
Case when Selection ='All Assets' then 'Other Assets'
When (IsAssetCode =1 and Selection <> 'ALL ASSETS') THEN Selection
End as Level5
From ((Select (columns) from tbl where IsAssetCode = 0
EXCEPT
SELECT (Columns) FROM tbl where IsAssetCode = 1)
Union
Select (column) from tbl where IsAssetCode = 1
)
輸入數據:
B1 Black All Assets 0 B1 White All Assets 0 B1 Red All Assets 0 B1 Black Core Asset 1
期望輸出:
B1 Black Core Asset 1 B1 White Other Asset 2 B1 Red Other Asset 2
請始終標記使用的 RDBMS,我假設 SQL-Server。
不滿足任何條件時CASE EXPRESSION
的默認值是NULL
,所以我的猜測 - 所有帶有“ALL ASSETS”的行都具有IsAssetCode
<> 1 對嗎?
要覆蓋它,您可以使用ELSE
:
CASE WHEN <Cond> Then <FirstVal>
WHEN <Cond2> Then <SecondVal>
ELSE <IfNonOfAboveVal>
END
或者只是提供不同的條件來捕獲所有內容。
只需使用 COUNT() 和 GROUP BY 即可獲得所需的計數
SELECT *,
CASE WHEN selection = 'All Assets'
THEN 'Other Assets'
WHEN (isassetcode = 1 AND selection <> 'All Assets')
THEN selection
END AS Level5,
COUNT(*) cnt
FROM table --or sub-query
GROUP BY list all columns in the select that corresponds the *,
CASE WHEN selection = 'All Assets'
THEN 'Other Assets'
WHEN (isassetcode = 1 AND selection <> 'All Assets')
THEN selection
END
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.