簡體   English   中英

列組中的子句

[英]Where Clause On Group Of Columns

我有一個零售商店的數據,下面的列

col_1   qty_1   col_2    qty_2    col_3     qty_3
Green   5       Red        8      Yellow     10

如果我想知道綠色的數量,那么我可以編寫一個簡單的查詢,其中col_1 ='綠色'。

但是我沒有在col_1中得到綠色的顏色代碼。 它將在col_1,col_2和col_3之間不斷改組,如下所示

col_1   qty_1   col_2    qty_2    col_3     qty_3
Green   5       Red        8      Yellow     10
Yellow  10      Green      7      Red        20

我怎樣才能有一個查詢來提取可用的綠色數量而不每次都更改查詢?

select case when col_1 = 'Green' then qty_1
            when col_2 = 'Green' then qty_2
            when col_3 = 'Green' then qty_3
       end as qty
from your_table
where 'Green' in (col_1, col_2, col_3)

要解決有關NULL值的問題,可以使用COALESCE()條件,如果為NULL則將為空白:

SELECT case when COALESCE(col_1,'') = 'Green' then qty_1
            when COALESCE(col_2,'') = 'Green' then qty_2
            when COALESCE(col_3,'') = 'Green' then qty_3
            end as qty
FROM your_table
WHERE 'Green' IN ( COALESCE(col_1,''), COALESCE(col_2,''), COALESCE(col_3,'') )
;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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