34,590
社区成员
发帖
与我相关
我的任务
分享
------------------------------------------------------------------------
-- Author: happyflystone
-- Date : 2009-04-30 16:14:54
-- Ver: Microsoft SQL Server 2005 - 9.00.2047.00 (Intel X86)
-- Apr 14 2006 01:12:25
-- Copyright (c) 1988-2005 Microsoft Corporation
-- Standard Edition on Windows NT 5.0 (Build 2195: Service Pack 4)
--
------------------------------------------------------------------------
-- Test Data: tA
IF OBJECT_ID('tA') IS NOT NULL
DROP TABLE tA
Go
CREATE TABLE tA(Tid INT,name NVARCHAR(3))
Go
INSERT INTO tA
SELECT 1,'aaa' UNION ALL
SELECT 2,'bbb' UNION ALL
SELECT 1,'ccc' UNION ALL
SELECT 2,'ddd'
GO
-- Test Data: tB
IF OBJECT_ID('tB') IS NOT NULL
DROP TABLE tB
Go
CREATE TABLE tB(Tid INT,otherfields NVARCHAR(3))
Go
INSERT INTO tB
SELECT 1,'xxx' UNION ALL
SELECT 2,'xxx'
GO
--Start
declare @s varchar(1000)
select @s= isnull(@s+',','')+'[name_'+ltrim(rid) +']= max(case when a.rid ='+ltrim(rid)+' then name else '''' end)'
from (
select distinct rid
from (select *,rid = (select count(1) from ta where a.tid = tid and name <= a.name)
from ta a
)c
) a
exec('select b.tid,b.otherfields,'+@s+ ' from (select *,rid = (select count(1) from ta where a.tid = tid and name <= a.name)
from ta a
) a,tb b where a.tid = b.tid group by b.tid,b.otherfields')
--Result:
/*
tid otherfields name_1 name_2
----------- ----------- ------ ------
1 xxx aaa ccc
2 xxx bbb ddd
*/
--End
printer 'select b.tid,b.otherfields,'+@s+ ' from (select *,rid = (select count(1) from ta where a.tid = tid and name <= a.name)
from ta a
) a,tb b where a.tid = b.tid group by b.tid,b.otherfields'