天天看點

sql 語句 CASE表達式用法1、case表達式:case簡單用法:

1、case表達式:

簡單CASE 表達式:

CASE sex

WHEN ‘1’ THEN ‘男’

WHEN ‘2’ THEN ‘女’

ELSE ‘其他’ END

搜尋CASE 表達式:

CASE sex

WHEN ‘1’ THEN ‘男’

WHEN ‘2’ THEN ‘女’

ELSE ‘其他’ END

注解:

簡單 CASE 表達式能寫的條件,搜尋 CASE 表達式也能寫

1、排他性

2、統一傳回資料類型

3、要寫END

4、養成寫ELSE的習慣,預設為NULL

case簡單用法:

eg1:将已有編号方式轉換為新的方式并統計

sql 語句 CASE表達式用法1、case表達式:case簡單用法:

SELECT *,case when pref_name in (‘蘇州’,‘南京’) then ‘江蘇’ when pref_name = ‘合肥’ then ‘安徽’ else ‘中國’ end as district,sum(population) as sum

from test.PopTbl group by district having sum >200 order by sum

注解: mysql資料庫 是先執行select子句,再執行group by的,是以拿新列group by,having也是

,sql/oracle反之

将行資料轉化成列資料

eg2:用一條 SQL 語句進行不同條件的統計(聚合函數使用case)

sql 語句 CASE表達式用法1、case表達式:case簡單用法:

select sum(case when sex =1 then case when population>0 then population else 0 end else 0 end) as ‘男’,sum(case when sex =2 then population else 0 end) as ‘女’,pref_name from test.PopTbl group by pref_name order by pref_name

注解:union也可

可嵌套 case when then else end 多條件限制(蘊含式)

蘊含式和邏輯與(logical product)的差別。邏輯與也是一個邏輯表達式,意思是“P 且 Q”,記作 P ∧ Q。蘊含式 P→Q

eg3:在 UPDATE 語句裡進行條件分支

sql 語句 CASE表達式用法1、case表達式:case簡單用法:

update test.salaries set salary = case when salary >=300000 then salary * 0.9 when salary

<250000 then salary * 1.2 else salary end where id>0

同 select 多個條件分支查詢 應用範圍:調換