当前位置: 代码迷 >> Sql Server >> sql 单列转行,该怎么处理
  详细解决方案

sql 单列转行,该怎么处理

热度:11   发布时间:2016-04-24 10:10:56.0
sql 单列转行
假如,查出的结果是
1
2
3
4
我想让它显示为1,2,3,4
请问这sql怎么写?
------解决方案--------------------
----------------------------------------------------------------
-- Author  :DBA_HuangZJ(發糞塗牆)
-- Date    :2014-07-23 17:14:09
-- 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)
insert [huang]
select 1 union all
select 2 union all
select 3 union all
select 4
--------------开始查询--------------------------

declare @s nvarchar(4000)
set @s=''
Select     @s=@s+','+quotename('id'+CAST(id AS varchar))+'=max(case when [id]='+quotename([id],'''')+' then [id] else 0 end)'
from [huang] group by [id]
SET @s=SUBSTRING(@s,2,LEN(@s))
exec('select '+@s+' from [huang] ')
----------------结果----------------------------
/* 
id1         id2         id3         id4
----------- ----------- ----------- -----------
1           2           3           4

*/
  相关解决方案