若y您事先知道列中的所有值,然后您可以在查询中对它们进行硬编码。否则,它会变得更加复杂。这是Oracle SQL:
with my_data as
(select 'agra' city, 'atm' "type", 'X' "name" from dual union
select 'agra' city, 'branch' "type", 'X1' "name" from dual union
select 'delhi' city, 'atm' "type", 'X2' "name" from dual union
select 'agra' city, 'atm' "type", 'X3' "name" from dual union
select 'agra' city, 'atm' "type", 'X4' "name" from dual union
select 'delhi' city, 'branch' "type", 'X5' "name" from dual union
select 'chennai' city, 'branch' "type", 'X6' "name" from dual)
select city,
sum(decode("type", 'atm', 1, 0)) as ATM,
sum(decode("type", 'branch', 1, 0)) as branch
from my_data
group by city;
如果列数是未知的,Oracle有一个“PIVOT XML”声明,允许其返回所有的汇总数据保存在一个XML:
select * from my_data
PIVOT XML (count("name") for "type" in (ANY));
您可以使用EXTRACTVALUE()函数自己分析每列,但这仍然意味着您知道提前多少列。我相信Oracle SQL无法创建具有动态列数的数据透视表。它可以在PL/SQL中完成,但你可以使用游标动态连接你的SQL。
谢谢@Gordon Linoff。奇迹般有效 ! –