当前位置: 代码迷 >> Sql Server >> SQL 行转列 不依照首字母排序
  详细解决方案

SQL 行转列 不依照首字母排序

热度:83   发布时间:2016-04-24 09:22:40.0
SQL 行转列 不按照首字母排序
----------------------------------------------------------------
-- Author  :DBA_HuangZJ(發糞塗牆)
-- Date    :2014-09-02 10:55:30
-- 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)
--
----------------------------------------------------------------
--> 测试数据:[huang]
if object_id('[huang]') is not null drop table [huang]
go 
create table [huang]([ID] int,[姓名] varchar(4),[课程] varchar(4),[分数] int)
insert [huang]
select 1,'张三','语文',77 union all
select 2,'张三','数学',88 union all
select 3,'张三','英语',99 union all
select 4,'李四','语文',75 union all
select 5,'李四','数学',85
--------------开始查询--------------------------
declare @s nvarchar(4000)
set @s=''
Select     @s=@s+','+quotename([课程])+'=max(case when [课程]='+quotename([课程],'''')+' then [分数] else null end)'
from [huang] WHERE [姓名]='李四'   group by [课程]
exec('select row_number()over(order by getdate()) as id,[姓名]'+@s+' from [huang] where [姓名]=''李四''  group by [姓名]')
----------------结果----------------------------
/* 
id                   姓名   数学          语文
-------------------- ---- ----------- -----------
1                    李四   85          75
*/

这个行转列后,列名默认是按照首字母排序的吧,那如何不按照首字母排序,直接按照原表的顺序,使其得到的结果如下
----------------结果----------------------------
/* 
id                   姓名   语文          数学
-------------------- ---- ----------- -----------
1                    李四   75          85
*/
------解决思路----------------------
if object_id('[huang]') is not null drop table [huang]
go 
create table [huang]([ID] int,[姓名] varchar(4),[课程] varchar(4),[分数] int)
insert [huang]
select 1,'张三','语文',77 union all
select 2,'张三','数学',88 union all
select 3,'张三','英语',99 union all
select 4,'李四','语文',75 union all
select 5,'李四','数学',85
--------------开始查询--------------------------
declare @s nvarchar(4000)
set @s=''
Select     @s=@s+','+quotename([课程])+'=max(case when [课程]='+quotename([课程],'''')+' then [分数] else null end)'
from [huang] WHERE [姓名]='李四'   group by [课程] ORDER BY MIN(ID)
exec('select row_number()over(order by getdate()) as id,[姓名]'+@s+' from [huang] where [姓名]=''李四''  group by [姓名]')
加个排序即可
  相关解决方案