我有一个来自零售商店的数据,列在下面
col_1 qty_1 col_2 qty_2 col_3 qty_3
Green 5 Red 8 Yellow 10
如果我想知道Green的数量,那么我可以写一个简单的查询,其中col_1 ='Green'。
但我没有得到col_1中的颜色代码Green。它会在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,'') )
;