竖变横问题!!!

BackerCao 2005-09-19 09:14:03
a 1
b 2
c 3
d 4

变成:
a b c d
1 2 3 4

在SQL里如何实现? 狂谢
...全文
155 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
fansino 2005-09-19
  • 打赏
  • 举报
回复
请问能生成横向的视图?如何生成?
谢谢赐教!
wgsasd311 2005-09-19
  • 打赏
  • 举报
回复
如果就是两列,上面效果是达不到的,只少还有第三列(col3),所以代码如下:
declare @str varchar(8000)
set @str=''
select @str=@str+',['+col1+']=sum(case col1 when '''+col1+
''' then col1 end)' from tb1 broup by col1
set @str='select '+stuff(@str,1,1,'')+' from tb1 group by col3'
exec(@str)
samfeng_2003 2005-09-19
  • 打赏
  • 举报
回复
declare @s varchar(8000)
set @s = ''
select @s = @s +','+列1+'=isnull(sum(case when 列1='''+列1+''' then 列2 end),0)'
from 表 group by 列1
exec('select '+@s+' from 表)
wgsasd311 2005-09-19
  • 打赏
  • 举报
回复
declare @str varchar(8000)
set @str=''
select @str=@str+',['+col1+']=sum(case col1 when '''+col1+
''' then col1 end)' from tb1 broup by col1
set @str='select '+stuff(@str,1,1,'')+' from tb1 group by col1'
exec(@str)

27,579

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 应用实例
社区管理员
  • 应用实例社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧