日期:2014-05-17 浏览次数:20617 次
----------------------------
-- 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]