日期:2014-05-16  浏览次数:20602 次

求個SQL
t1      t2     t3
---------------------
A       BV   QW
A      CZ    FDSF
B       XM  WE
B      YO   RT3
A       ZZ   564
C      G     E

要求結果
t1      t2
-----------------------------------------
A       BV:QW CZ:FDSF ZZ:564
B       XM:WE YO:RT3
C      G:E

------解决方案--------------------
----------------------------------------------------------------
-- Author  :DBA_HuangZJ(发粪涂墙)
-- Date    :2014-03-14 08:29:24
-- Version:
--      Microsoft SQL Server 2008 R2 (RTM) - 10.50.1600.1 (X64) 
-- Apr  2 2010 15:48:46 
-- Copyright (c) Microsoft Corporation
-- Enterprise Edition (64-bit) on Windows NT 6.2 <X64> (Build 9200: ) (Hypervisor)
--
----------------------------------------------------------------
--> 测试数据[huang]
if object_id('[huang]') is not null drop table [huang]
go 
create table [huang]([t1] nvarchar(2),[t2] nvarchar(4),[t3] nvarchar(8))
insert [huang]
select 'A','BV','QW' union all
select 'A','CZ','FDSF' union all
select 'B','XM','WE' union all
select 'B','YO','RT3' union all
select 'A','ZZ','564' union all
select 'C','G','E'
--------------生成数据--------------------------

--select * from [huang]

select a.[t1],
stuff((select ' '+[t2]+':'+[t3] from [huang] b 
       where b.[t1]=a.[t1]
       for xml path('')),1,1,'') 't2'
from [huang] a
group by  a.[t1]
----------------结果----------------------------
/* 
t1   t2
---- ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
A    BV:QW CZ:FDSF ZZ:564
B    XM:WE YO:RT3
C    G:E
*/

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

WITH a1 (t1,t2,t3) AS
(
SELECT 'A','BV','QW' UNION ALL
SELECT 'A','CZ','FDSF' UNION ALL
SELECT 'B','XM','WE' UNION ALL
SELECT 'B','YO','RT3' UNION ALL
SELECT 'A','ZZ','564' UNION ALL
SELECT 'C','G','E'
)
SELECT t1,t2=
STUFF(
(SELECT ' '+t2+':'+t3 FROM a1 WHERE t1=a.t1 FOR XML PATH(''))
,1,1,'')
FROM a1 a
GROUP BY t1