Home > Database > Mysql Tutorial > body text

SQLServer行转列

WBOY
Release: 2016-06-07 15:51:49
Original
1184 people have browsed it

最近面试遇到了一道面试题,顿时有点迷糊,只说出了思路,后来百度了一下,整理了一下思路,于是记录下来,方便以后学习。(面试题请参见附件) 相关的数据表: 1.Score表 2.[User]表 SQL语句如下: --方法一:静态SQL SELECT * FROM (SELECT UID,Name, Scor

最近面试遇到了一道面试题,顿时有点迷糊,只说出了思路,后来百度了一下,整理了一下思路,于是记录下来,方便以后学习。(面试题请参见附件)

相关的数据表:

1.Score表

SQLServer行转列

2.[User]表

SQLServer行转列

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

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template