一条mssql 语句 行转列

hai_na_bai_chuan_ 2016-08-09 10:31:45
x y
------------------------
1 a
2 b
3 c
4 d


结果
a1 a2 a3 a4
---------------------
a b c d
...全文
268 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
中国风 2016-08-09
  • 打赏
  • 举报
回复
这语句不能固定写死,应该 用动态
hai_na_bai_chuan_ 2016-08-09
  • 打赏
  • 举报
回复
select max(case when x = 1 then y end) as a1, max(case when x = 2 then y end) as a2, max(case when x = 3 then y end) as a3, max(case when x = 4 then y end) as a4 from v --- group by y 我也很纳闷啊,这么简单的语句,画蛇添足加了 group by y 谢谢了,讲的十分详细
LongRui888 2016-08-09
  • 打赏
  • 举报
回复
其实行转列,就是分组(一般会有group by xx字段)之后,通过聚合函数,一般是max,min,如果同时有计数、求和,就用count,sum。
LongRui888 2016-08-09
  • 打赏
  • 举报
回复
试试这个:
select max(case when x = 1 then y end) as a1,
       max(case when x = 2 then y end) as a2,
       max(case when x = 3 then y end) as a3,
       max(case when x = 4 then y end) as a4       
from 
(
select 1  as x ,'a' as y union all
select 2   ,'b' union all
select 3   ,'c' union all
select 4   ,'d'
)v
/*
a1	a2	a3	a4
a	b	c	d
*/

22,209

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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