簡體   English   中英

使用 Case 語句時獲取空值

[英]Getting Null values when using Case statement

我正在嘗試根據另一列( SelectionIsAssetCode )派生一列( Level5 )。

Selection列有兩種類型的條目 - “所有資產”和“核心資產”,並且IsAssetCode01 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM