日期:2014-05-18 浏览次数:20546 次
create table #t1 ( fid int identity(1,1), fcardnumber varchar(10), funitnumber varchar(10), ftime datetime not null ) go insert into #t1 select 'Card001','Unit003','2012-04-05 08:03:12.350' insert into #t1 select 'Card001','Unit002','2012-03-15 08:13:15.730' insert into #t1 select 'Card001','Unit001','2012-02-25 08:15:18.130' insert into #t1 select 'Card002','Unit005','2012-04-05 08:03:12.350' insert into #t1 select 'Card002','Unit003','2012-03-15 08:13:15.730' insert into #t1 select 'Card002','Unit002','2012-02-25 08:15:18.130' insert into #t1 select 'Card002','Unit004','2012-01-25 08:15:18.130' ;with t as( select fcardnumber,funitnumber from( select *,ROW_NUMBER()over(partition by fcardnumber order by ftime desc) as row_num from #t1)a where row_num<=2 ) select fcardnumber,REPLACE(funitnumber,'<',' ') as funitnumber from( SELECT *FROM (SELECT DISTINCT fcardnumber FROM t)A OUTER APPLY( SELECT funitnumber= STUFF(REPLACE(REPLACE( ( SELECT funitnumber FROM t N WHERE fcardnumber = A.fcardnumber FOR XML AUTO ), '_x0023_t1 funitnumber="', ''), '"/>', ''), 1, 1, '') )N)a /* fcardnumber funitnumber Card001 Unit003 Unit002 Card002 Unit005 Unit003 */
------解决方案--------------------
你的 库版本估计不是 SQL 2008 或2005.如果是的话,执行是没有问题的。