当前位置: 代码迷 >> Sql Server >> sql多行记要合并成一条
  详细解决方案

sql多行记要合并成一条

热度:78   发布时间:2016-04-24 19:38:41.0
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
/*
S1 S2 S3
100 200 300
*/
  相关解决方案