最近面試遇到了一道面試題,頓時(shí)有點(diǎn)迷糊,只說出了思路,后來百度了一下,整理了一下思路,于是記錄下來,方便以后學(xué)習(xí)。(面試題請參見附件)
相關(guān)的數(shù)據(jù)表:
1.Score表
2.[User]表
SQL語句如下:
--方法一:靜態(tài)SQL
復(fù)制代碼 代碼如下:
SELECT * FROM
(SELECT UID,Name, Score,ScoreName FROM Score,[User] WHERE Score.UID=[User].ID) AS SourceTable
PIVOT(AVG(Score)FOR ScoreName IN ([英語], [數(shù)學(xué)])) AS a
--方法二:動態(tài)SQL
復(fù)制代碼 代碼如下:
DECLARE @s NVARCHAR(4000)
SELECT @s = ISNULL(@s + ',', '') + QUOTENAME(ScoreName)
FROM (select distinct ScoreName from Score) as A ---列名不要重復(fù)
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
復(fù)制代碼 代碼如下:
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 '數(shù)學(xué)' then Score else 0 end) 數(shù)學(xué)
from Score,[User] WHERE Score.UID=[User].ID
group by UID,[User].ID,Name
您可能感興趣的文章:- mysql 行轉(zhuǎn)列和列轉(zhuǎn)行實(shí)例詳解
- sql語句實(shí)現(xiàn)行轉(zhuǎn)列的3種方法實(shí)例
- MySQL存儲過程中使用動態(tài)行轉(zhuǎn)列
- mssql 數(shù)據(jù)庫表行轉(zhuǎn)列,列轉(zhuǎn)行終極方案
- Sql Server 2000 行轉(zhuǎn)列的實(shí)現(xiàn)(橫排)
- SQL查詢語句行轉(zhuǎn)列橫向顯示實(shí)例解析
- sql動態(tài)行轉(zhuǎn)列的兩種方法
- table 行轉(zhuǎn)列的sql詳解
- SQL行轉(zhuǎn)列和列轉(zhuǎn)行代碼詳解
- SQL基礎(chǔ)教程之行轉(zhuǎn)列Pivot函數(shù)