[英]Getting Null values when using Case statement
I am trying to derive a column ( Level5
) based on another columns ( Selection
and IsAssetCode
).我正在尝试根据另一列(
Selection
和IsAssetCode
)派生一列( Level5
)。
Selection
column has two types of entries - "All Asset" and "Core Asset", and IsAssetCode
is 0
or 1
. Selection
列有两种类型的条目 - “所有资产”和“核心资产”,并且IsAssetCode
是0
或1
。 IsAssetCode = 0
corresponds to "All Asset," and 1
is "Core Asset". IsAssetCode = 0
对应“所有资产”, 1
是“核心资产”。
I am trying to separate Core and Non-core assets but I am getting extra rows with "All Assets" in Level5
.我试图将核心资产和非核心资产分开,但我在
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
)
Input data:输入数据:
B1 Black All Assets 0 B1 White All Assets 0 B1 Red All Assets 0 B1 Black Core Asset 1
Desired Output:期望输出:
B1 Black Core Asset 1 B1 White Other Asset 2 B1 Red Other Asset 2
Please always tag the RDBMS used, I assume SQL-Server.请始终标记使用的 RDBMS,我假设 SQL-Server。
The default value of a CASE EXPRESSION
when no conditions are met is NULL
, so my guess - all the rows with "ALL ASSETS" has IsAssetCode
<> 1 right?不满足任何条件时
CASE EXPRESSION
的默认值是NULL
,所以我的猜测 - 所有带有“ALL ASSETS”的行都具有IsAssetCode
<> 1 对吗?
To override this, you can use the ELSE
:要覆盖它,您可以使用
ELSE
:
CASE WHEN <Cond> Then <FirstVal>
WHEN <Cond2> Then <SecondVal>
ELSE <IfNonOfAboveVal>
END
Or just provide a different condition to catch everything.或者只是提供不同的条件来捕获所有内容。
Just use COUNT() and GROUP BY to get the desired count只需使用 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.