Case comes in two formats. Simple Case functions and Case search functions.
--Simple Case function
CASE sex
WHEN '1' THEN '男'
WHEN '2' THEN '女'
ELSE 'other' END
--Case search function
CASE WHEN sex = '1' THEN '男'
WHEN sex = '2' THEN '女'
ELSE 'other' END
These two methods can achieve the same function. The writing method of the simple case function is relatively simple, but compared with the case search function, there are some limitations in functions, such as writing judgments.
There is also a problem to pay attention to, the Case function only returns the first value that meets the condition, and the rest of the Case part will be automatically ignored.
--For example, in the following SQL, you can never get the result of "second type"
CASE WHEN col_1 IN ( 'a', 'b') THEN 'first class'
WHEN col_1 IN ('a') THEN 'Second class'
ELSE 'other' END
sql 语句错误
select case sales_type
when 'S' then 'Supply agreement'
when 'C' then 'Outright purchase'
end,
case adidas_division
when 'Footwear' then 'Footwear'
when 'AandG' then 'A&G'
when 'Apparel' then 'Apparel'
else '-'
end
into machine_report from machine_records join retailers on machine_records.retailer_id=retailers.retailer_id
报错 column "case" specified more than once
------解决方案--------------------
SELECT (CASE WHEN sales_type = 'S' THEN 'Supply agreement'
WHEN sales_type = 'C' THEN 'Outright purchase'
END) AS a,
(CASE WHEN adidas_division='Footwear' THEN 'Footwear'
WHEN adidas_division='AandG' THEN 'A&G'
WHEN adidas_division='Apparel' THEN 'Apparel'
ELSE '-'
END) b 试试