《Sql中的行列转》

—行转列
创建实例表:
create multiset volatile table vt1 (
cust_id varchar(10)
,class varchar(10)
,score deciaml(18,2)
)primary index(cust_id)
;

Insert into vt1 values (‘101’,’语文’,93);
Insert into vt1 values (‘101’,’数学,90);
Insert into vt1 values (‘101’,’英语’,89);

Insert into vt1 values (‘102,’语文’,83);
Insert into vt1 values (‘102’,’数学,91);
Insert into vt1 values (‘102’,’英语’,79);

Select
cust_id
, sum(case when class=‘语文’ then score else 0 end ) as “语文”
, sum(case when class=‘数学’ then score else 0 end )as “数学”
, sum(case when class=‘英语’ then score else 0 end ) as “英语”
from vt1
Group 1
;

—列转行操作

create multiset volatile table vt2 as (
Cust_id varchar(10)
,class_a decimal(10,2)
,class_b decimal(10,2)
,class_c decimal(10,2)
) primary index(cust_id) on commit preserve rows;

Insert into vt1 values (‘101,90,87,80);
Insert into vt1 values (‘102,83,91,90);

Select cuse_id , ’语文’,class_a from vt2 union
Select cuse_id , ’’数学, class_b from vt2 union
Select cuse_id , ’’英语, class_c from vt2

;

你可能感兴趣的:(笔记)