简体   繁体   English

使用 Case 语句时获取空值

[英]Getting Null values when using Case statement

I am trying to derive a column ( Level5 ) based on another columns ( Selection and IsAssetCode ).我正在尝试根据另一列( SelectionIsAssetCode )派生一列( Level5 )。

Selection column has two types of entries - "All Asset" and "Core Asset", and IsAssetCode is 0 or 1 . Selection列有两种类型的条目 - “所有资产”和“核心资产”,并且IsAssetCode01 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM