日期:2014-05-17  浏览次数:20415 次

sql多行记录合并成一条
CountStates statesname
100            S1
200            S2
300            S3

需要合并成

S1   S2  S3
100 200 300

------解决方案--------------------
SELECT SUM(CASE WHEN statesname='S1' THEN CountStates ELSE 0 END) AS 'S1'
,SUM(CASE WHEN statesname='S2' THEN CountStates ELSE 0 END) AS 'S2'
,SUM(CASE WHEN statesname='S3' THEN CountStates ELSE 0 END) AS 'S3'
FROM TB

------解决方案--------------------
来个动态的
----------------------------------------------------------------
-- Author  :DBA_Huangzj(發糞塗牆)
-- Date    :2013-11-29 16:34:47
-- Version:
--      Microsoft SQL Server 2012 (SP1) - 11.0.3128.0 (X64) 
-- Dec 28 2012 20:23:12 
-- Copyright (c) Microsoft Corporation
-- Enterprise Edition (64-bit) on Windows NT 6.2 <X64> (Build 9200: )
--
----------------------------------------------------------------
--> 测试数据:[huang]
if object_id('[huang]') is not null drop table [huang]
go 
create table [huang]([CountStates] int,[statesname] varchar(2))
insert [huang]
select 100,'S1' union all
select 200,'S2' union all
select 300,'S3'
--------------开始查询--------------------------

 
declare @s nvarchar(4000)
set @s=''
Select     @s=@s+','+quotename([statesname])+'=max(case when [statesname]='+quotename([statesname],'''')+' then [CountStates] else 0 end)'
from [huang] group by [statesname]
SET @s=SUBSTRING(@s,2,LEN(@s))
exec('select '+@s+' from [huang] ')
----------------结果----------------------------
/* 
S1          S2          S3
----------- ----------- -----------
100         200         300
*/

------解决方案--------------------

CREATE TABLE #T_A(
    statesname varchar(200)
    , &nbs