关于SQL中如何将结果横向显示
如何将第一个图中的数据以第二个图中的形式输出?用下面的SQL无法实现,是什么原因?正确的应该怎么写?selecta.id,max(casewhena.seq=1thena...
如何将第一个图中的数据以第二个图中的形式输出? 用下面的SQL无法实现,是什么原因? 正确的应该怎么写?
select a.id,max(case when a.seq=1 then a.name end),max(case when a.seq=2 then a.name end),max(case when a.seq=3 then a.name end)
from (select id,name,row_number()over(partition by id order by name) seq from #table) a 展开
select a.id,max(case when a.seq=1 then a.name end),max(case when a.seq=2 then a.name end),max(case when a.seq=3 then a.name end)
from (select id,name,row_number()over(partition by id order by name) seq from #table) a 展开
2个回答
展开全部
declare @sql varchar(400),@sql1 varchar(4000)
set @sql = 'select id,name,row_number()over(partition by id order by name) seq from #table
set @sql1 = 'select table1.ID,table_1.name name1,table_2.name name2,table_3.name name3
from (select id from ('+@sql+')table1 group by ID) table1
left join ('+@sql+') table_1 on table1.id =table_1.id and table_1.seq = 1
left join ('+@sql+') table_2 on table1.id =table_2.id and table_2.seq = 2
left join ('+@sql+') table_3 on table1.id =table_3.id and table_3.seq = 3 '
exec (@sql1) ;
set @sql = 'select id,name,row_number()over(partition by id order by name) seq from #table
set @sql1 = 'select table1.ID,table_1.name name1,table_2.name name2,table_3.name name3
from (select id from ('+@sql+')table1 group by ID) table1
left join ('+@sql+') table_1 on table1.id =table_1.id and table_1.seq = 1
left join ('+@sql+') table_2 on table1.id =table_2.id and table_2.seq = 2
left join ('+@sql+') table_3 on table1.id =table_3.id and table_3.seq = 3 '
exec (@sql1) ;
2014-04-10
展开全部
这是交叉表。
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询