列变行

create table test
(RssID int,
 RssName varchar(20),
 Tid int)
insert test
select 1,'新闻',44792 union all
select 1,'新闻',62732 union all
select 1,'新闻',88147 union all
select 2,'社会',23231 union all
select 2,'社会',17452 union all
select 3,'足坛',22181 union all
select 3,'足坛',61333 union all
select 3,'足坛',32211

select *,id=IDENTITY(int) into # from test

declare @sql varchar(8000),@maxcnt int,@temp int
select @sql='',@temp=1,@maxcnt=max(cnt) from(select count(*) cnt from # group by RssID,RssName) as a
--返回最大列值
/*????
''   1    3
*/
print @sql
print @temp
print @maxcnt

--设置最大列
while(@temp<=@maxcnt)
begin
set @sql=@sql+',isnull(max(case when Tid_cnt='+rtrim(@temp)
             +' then Tid else null end),''8'') as [Tid'+rtrim(@temp)+']'
set @temp=@temp+1
end
print @sql

exec ('select RssID,RssName'+@sql+' from (select RssID,RssName,Tid,(select count(*) from # where RssID=a.RssID and RssName=a.RssName and id<=a.id)[Tid_cnt] from # a)a group by RssID,RssName order by RssID')

 

--select RssID,RssName,Tid,(select count(*) from # where RssID=a.RssID and RssName=a.RssName and id<=a.id) as [Tid_cnt] from # a
select RssID,RssName,Tid,(select count(*) from # where RssID=a.RssID and RssName=a.RssName and id<=a.id) as [Tid_cnt] from # a
select RssID,RssName,Tid [Tid_cnt] from # a
select count(*) from # a where RssID=a.RssID and RssName=a.RssName


select (select count(*) from # where  RssID=a.RssID  and id<=a.id) as [Tid_cnt] from # a
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值