SQLServer行轉列完成思緒記載。本站提示廣大學習愛好者:(SQLServer行轉列完成思緒記載)文章只能為提供參考,不一定能成為您想要的結果。以下是SQLServer行轉列完成思緒記載正文
比來面試碰到了一道面試題,馬上有點含混,只說出了思緒,後來百度了一下,整頓了一下思緒,因而記載上去,便利今後進修。(面試題請拜見附件)
相干的數據表:
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