日期:2014-05-18 浏览次数:20783 次
--result /*用户id 商品一 商品二 ------------------------------ ------------------------------ ------------------------------ user1 名称1 名称5 user2 名称4 名称3 */
------解决方案--------------------
create table tb(商品ID varchar(10),用户ID varchar(10),商品名称 varchar(10),添加日期 datetime)
insert into tb values('0001','user1','名称1','2007-10-10')
insert into tb values('0002','user2','名称2','2007-10-11')
insert into tb values('0003','user2','名称3','2007-10-12')
insert into tb values('0004','user2','名称4','2007-10-13')
insert into tb values('0005','user1','名称5','2007-10-14')
go
--只显示前两个(1,2)
select 用户ID,
max(case px when 1 then 商品名称 else '' end) '商品一',
max(case px when 2 then 商品名称 else '' end) '商品二'
from
(
select px=(select count(1) from tb where 用户ID=a.用户ID and 添加日期>a.添加日期)+1 , 用户ID,商品名称 from tb a
) t
group by 用户ID
/*
用户ID 商品一 商品二
---------- ---------- ----------
user1 名称5 名称1
user2 名称4 名称3
(所影响的行数为 2 行)
*/
--如果都要显示,得用动态SQL
declare @sql varchar(8000)
set @sql = 'select 用户ID'
select @sql = @sql + ' , max(case px when ''' + cast(px as varchar) + ''' then 商品名称 else '' '' end) [商品' + cast(px as varchar) + ']'
from (select distinct px from (select px=(select count(1) from tb where 用户ID=a.用户ID and 添加日期>a.添加日期)+1 , 用户ID,商品名称 from tb a) t ) as a
set @sql = @sql + ' from (select px=(select count(1) from tb where 用户ID=a.用户ID and 添加日期>a.添加日期)+1 , 用