当前位置: 代码迷 >> Sql Server >> sql 列转行有关问题
  详细解决方案

sql 列转行有关问题

热度:86   发布时间:2016-04-24 10:15:06.0
sql 列转行问题

嗯,这是我昨天在论坛里看到的问题,很感兴趣,自己试了下,发现那个列名好像很难弄。
今天上论坛没找到原帖,所以发一个。
要求结果是:
班长           体育委员            文娱委员            学习委员

刘备           张飞                    貂蝉                   诸葛亮



求大神指导下!


------解决方案--------------------
那要用动态
----------------------------------------------------------------
-- Author  :DBA_HuangZJ(發糞塗牆)
-- Date    :2014-07-31 14:48:44
-- Version:
--      Microsoft SQL Server 2012 - 11.0.5058.0 (X64) 
-- May 14 2014 18:34:29 
-- Copyright (c) Microsoft Corporation
-- Enterprise Edition: Core-based Licensing (64-bit) on Windows NT 6.3 <X64> (Build 9600: ) (Hypervisor)
--
----------------------------------------------------------------
--> 测试数据:[A]
if object_id('[A]') is not null drop table [A]
go 
create table [A]([stu_id] int,[stuName] varchar(6))
insert [A]
select 1,'关羽' union all
select 2,'诸葛亮' union all
select 3,'貂蝉' union all
select 4,'刘备' union all
select 5,'张飞'
--> 测试数据:[B]
if object_id('[B]') is not null drop table [B]
go 
create table [B]([zhiwu] varchar(8),[stu_id] int)
insert [B]
select '班长',4 union all
select '体育委员',5 union all
select '文娱委员',3 union all
select '学习委员',2
--------------开始查询--------------------------

--select '班长'=MAX(CASE WHEN zhiwu='班长' THEN stuname ELSE NULL END ),
--'体育委员'=MAX(CASE WHEN zhiwu='体育委员' THEN stuname ELSE NULL END ),
--'文娱委员'=MAX(CASE WHEN zhiwu='文娱委员' THEN stuname ELSE NULL END ),
--'学习委员'=MAX(CASE WHEN zhiwu='学习委员' THEN stuname ELSE NULL END )
--from [B] LEFT JOIN [A] ON b.stu_id=a.stu_id

declare @s nvarchar(4000)
set @s=''
Select     @s=@s+','+quotename([zhiwu])+'=max(case when [zhiwu]='+quotename(zhiwu,'''')+' then [stuname] else null end)'
from (SELECT zhiwu,stuname from [B] LEFT JOIN [A] ON b.stu_id=a.stu_id)a group by zhiwu
SET @s=SUBSTRING(@s,2,LEN(@s))
exec('select '+@s+' from (SELECT zhiwu,stuname  from [B] LEFT JOIN [A] ON b.stu_id=a.stu_id)a ')


----------------结果----------------------------
/* 
班长     体育委员   文娱委员   学习委员
------ ------ ------ ------
刘备     张飞     貂蝉     诸葛亮
*/
  相关解决方案