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)
, CountStates INT
)
INSERT INTO #T_A
SELECT 'S1',100
UNION
SELECT 'S2',200
UNION
SELECT 'S3',300
--select * from #T_A
declare @sql varchar(max)
set @sql=''
select @sql=@sql + ',['+rtrim(statesname)+']=sum(case statesname when '''+rtrim(statesname)+''' then CountStates else 0 end)'
from #T_A group by statesname
exec('select ''1'' as id'+@sql+'from #T_A ' )
DROP TABLE #T_A
(3 行受影响)
id S1 S2 S3
---- ----------- ----------- -----------
1 100 200 300
(1 行受影响)
create table tb(CountStates int,statesname varchar(10))
insert into tb
select 100 , 'S1'
union all select 200, 'S2'
union all select 300, 'S3'
select *
from tb
pivot
(
sum(CountStates) for statesname in ([S1],[S2],[S3])
)X
/*
S1S2S3
100200300
*/