最近面試遇到了一道面試題,頓時有點迷糊,只說出了思路,後來百度了一下,整理了一下思路,於是記錄下來,方便以後學習。(面試題請參見附件)
相關的數據表:
1.Score表
2.[User]表
SQL語句如下:
--方法一:靜態SQL
復制代碼 代碼如下:
SELECT * FROM
(SELECT UID,Name, Score,ScoreName FROM Score,[User] WHERE Score.UID=[User].ID) AS SourceTable
PIVOT(AVG(Score)FOR ScoreName IN ([英語], [數學])) AS a
--方法二:動態SQL
復制代碼 代碼如下:
DECLARE @s NVARCHAR(4000)
SELECT @s = ISNULL(@s + ',', '') + QUOTENAME(ScoreName)
FROM (select distinct ScoreName from Score) as A ---列名不要重復
Declare @sql NVARCHAR(4000)
SET @sql='
select r.* from
(select UID,Name,ScoreName,Score from Score,[User] where Score.UID=[User].ID) as t
pivot
(
max(t.Score)
for t.ScoreName in ('+@s+')
) as r'
EXEC( @sql)
--方法三:Case When
復制代碼 代碼如下:
select
row_number() OVER(ORDER BY [User].ID) as 編號,
UID as 用戶編號,
Name as 姓名,
max(case ScoreName when '英語' then Score else 0 end) 英語,
max(case ScoreName when '數學' then Score else 0 end) 數學
from Score,[User] WHERE Score.UID=[User].ID
group by UID,[User].ID,Name