1. 程式人生 > 實用技巧 >sql面試 case /union all

sql面試 case /union all

1、sum(case when results='勝' then 1 else 0 end) as ‘勝’

要求查詢出結果:

sql語句實現:

select date,
	sum(case when results='勝' then 1 else 0 end) AS '勝',
	sum(case when results='負' then 1 else 0 end) AS '負'
from game
group by date;

2、成績分等級(case when 條件 then 結果 when 條件 then 結果 else 結果 end)

請寫出生成如下圖結果的sql語句( >=80 表示優秀, >=60 且 <80表示及格,<60表示不及格)?

效果圖:

sql語句實現:

select 
	(case when `語文` >= 80 then '優秀' when `語文` >= 60 then '及格' else '不及格' end) AS '語文',
	(case when `數學` >= 80 then '優秀' when `數學` >= 60 then '及格' else '不及格' end) AS '數學',
  (case when `英語` >= 80 then '優秀' when `英語` >= 60 then '及格' else '不及格' end) AS '英語'
from score

3、合併欄位顯示(union all)

合併顯示按投資額度倒序排序,結果如下:

sql語句實現

select 
	id AS '編號',
	'db_gain' AS '表名',
	'' as '連線',
	invest_money AS '投資額度',
	project_name as '專案名稱',
	belongs_inductry as '產業領域',
	coperation as '合作方式'
from db_gain
UNION ALL
select 
	id AS '編號',
	'achievement' as '表名',
	url as '連線',
	price as '投資額度',
	name as '專案名稱',
	category as '產業領域',
	tradeType as '合作方式'
from achievement
order by `投資額度` desc;