微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

SQLServer行转列实现思路记录

最近面试遇到了一道面试题,顿时有点迷糊,只说出了思路,后来百度了一下,整理了一下思路,于是记录下来,方便以后学习。(面试题请参见附件) 相关的数据表: 1.score
<IMG src="https:https://files.jb51.cc/file_images/article/201406/20140617093835.jpeg?20145179404"&gt;
2.[User]表
<IMG src="https:https://files.jb51.cc/file_images/article/201406/20140617094025.jpeg?201451794045"&gt;
sql语句如下: --方法一:静态sql
<div class="codetitle"><a style="CURSOR: pointer" data="91090" class="copybut" id="copybut91090" onclick="doCopy('code91090')"> 代码如下:

<div class="codebody" id="code91090">
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
<div class="codetitle"><a style="CURSOR: pointer" data="82804" class="copybut" id="copybut82804" onclick="doCopy('code82804')"> 代码如下:
<div class="codebody" id="code82804">
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,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
<div class="codetitle"><a style="CURSOR: pointer" data="60777" class="copybut" id="copybut60777" onclick="doCopy('code60777')"> 代码如下:
<div class="codebody" id="code60777">
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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

行转列

相关推荐