我的表格包含以下详细信息:
表:ftest
create table ftest
(
cola varchar(10),
colb varchar(10)
)
插入记录:
insert into ftest values('A10','JK1');
insert into ftest values('A10','JK2');
insert into ftest values('A10','JK3');
insert into ftest values('A10','JK4');
insert into ftest values('A10','JK1');
数据透视表脚本:
select cola,JK1,JK2,JK3,JK4
from
(
select cola,colb
from ftest
)p
pivot
(
count(colb)
for colb in (JK1,JK2,JK3,JK4)
) as pvt;
获得结果:
cola JK1 JK2 JK3 JK4
------------------------
A10 2 1 1 1
预期结果:
我想对所有列JK1,JK2,JK3,JK4
的值求和,并为其指定SUM
列。
cola JK1 JK2 JK3 JK4 SUM
-----------------------------
A10 2 1 1 1 5
答案 0 :(得分:3)
您可以通过几种不同的方式获得“总计”列。
您可以在最终选择列表中将每个列添加到一起:
select cola,JK1,JK2,JK3,JK4,
Total = JK1+JK2+JK3+JK4
from
(
select cola,colb
from ftest
)p
pivot
(
count(colb)
for colb in (JK1,JK2,JK3,JK4)
) as pvt;
请参阅Demo
或者您可以使用COUNT() OVER()
之类的窗口函数来获取每个cola
分区的总数:
select cola,JK1,JK2,JK3,JK4, Total
from
(
select cola,colb,
Total = count(*) over(partition by cola)
from ftest
)p
pivot
(
count(colb)
for colb in (JK1,JK2,JK3,JK4)
) as pvt;
见Demo。两者都给出了结果:
| COLA | JK1 | JK2 | JK3 | JK4 | TOTAL |
|------|-----|-----|-----|-----|-------|
| A10 | 2 | 1 | 1 | 1 | 5 |