sql行转列的3种方法
行转列的3种方法max(case when)pivot()用存储过程行转列准备数据--创建表create table Table_A(商家 string,奶茶 string,价格 bigint);--插入数据insert into Table_A(商家,奶茶,价格) values('1点点','波霸奶茶',14),('1点点','四季奶青',14),('喜茶','波霸奶茶',21),('CoCo'
·
行转列的3种方法
-
max(case when)
-
pivot()
-
用存储过程行转列
准备数据
--创建表
create table Table_A
(
商家 string,
奶茶 string,
价格 bigint
);
--插入数据
insert into Table_A(商家,奶茶,价格) values
('1点点','波霸奶茶',14),
('1点点','四季奶青',14),
('喜茶','波霸奶茶',21),
('CoCo','四季奶青',16);
--查询数据
select * from Table_A ;
行转列-方法1:max(case when)
select
商家,
max(case when 奶茶='波霸奶茶' then 价格 end) as 波霸奶茶,
max(case when 奶茶='四季奶青' then 价格 end) as 四季奶青
from Table_A group by 商家;
行转列-方法2:pivot()
select * from Table_A pivot(max(价格) for 奶茶 in (波霸奶茶,四季奶青)) a;
--我这边使用的sql不支持使用pivot(),此语句的正确性有待验证;
行转列-方法3:用存储过程
alter proc pro_test
@userImages varchar(200),
@奶茶 varchar(20),
@奶茶1 varchar(200),
@TableName varchar(50)
as
declare @sql varchar(max)='select * from (select '+@userImages+' from'+@TableName+') tab
pivot
(
sum('+@奶茶+') for 奶茶('+@奶茶1+')
) pvt'
exec (@sql)
go
exec pro_test '商家,奶茶,价格',
'Table_A',
'奶茶',
'波霸奶茶,四季奶青'
;
--我这边使用的sql不支持使用存储过程,此语句的正确性有待验证;
更多推荐
已为社区贡献1条内容
所有评论(0)