table1
ndb004 ndb005 ndb006 NDB007
20130302 660221 1
20130303 660102 -1 103
20130303 660204 1
20130303 660206 1
20130303 660204 -1
20130303 660221 1
20130303 660204 1
20130303 100101 -1 201
在数据库里直接得到这个表
talbe2
ndb004 ndb005 ndb006
20130302 660221 -1
20130303 660221,660204,660206,660204,660221,660204 -1
sql语句
------解决方案--------------------
----------------------------
-- Author :DBA_Huangzj(發糞塗牆)
-- Date :2013-05-28 11:42:30
-- Version:
-- Microsoft SQL Server 2008 R2 (SP1) - 10.50.2500.0 (X64)
-- Jun 17 2011 00:54:03
-- Copyright (c) Microsoft Corporation
-- Enterprise Edition (64-bit) on Windows NT 6.1 <X64> (Build 7601: Service Pack 1, v.721)
--
----------------------------
--> 测试数据:[table1]
if object_id('[table1]') is not null drop table [table1]
go
create table [table1]([ndb004] datetime,[ndb005] int,[ndb006] int,[NDB007] int)
insert [table1]
select '20130302',660221,1,null union all
select '20130303',660102,-1,103 union all
select '20130303',660204,1,null union all
select '20130303',660206,1,null union all
select '20130303',660204,-1,null union all
select '20130303',660221,1,null union all
select '20130303',660204,1,null union all
select '20130303',100101,-1,201
--------------开始查询--------------------------
SELECT a.[ndb004] ,
STUFF(( SELECT ',' + CONVERT(VARCHAR(128),[ndb005])
FROM [table1] b
WHERE b.[ndb004] = a.[ndb004]
AND b.[ndb006] = a.[ndb006]
FOR
XML PATH('')
), 1, 1, '') '[ndb005]', a.[ndb006]
FROM [table1] a
GROUP BY a.[ndb004] ,