I am trying to derive a column ( Level5
) based on another columns ( Selection
and IsAssetCode
).
Selection
column has two types of entries - "All Asset" and "Core Asset", and IsAssetCode
is 0
or 1
. IsAssetCode = 0
corresponds to "All Asset," and 1
is "Core Asset".
I am trying to separate Core and Non-core assets but I am getting extra rows with "All Assets" in 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.
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?
To override this, you can use the 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
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.