SQLServer行轉列

來源:互聯網
上載者:User

最近面試遇到了一道面試題,頓時有點迷糊,只說出了思路,後來百度了一下,整理了一下思路,於是記錄下來,方便以後學習。(面試題請參見附件)

相關的資料表:

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.