具有多个求和列的 Oracle SQL PIVOT



我有一张这样的桌子...

create table my_table_for_pivot (month date, country varchar2(40),metric1, metric2);
insert into my_table_for_pivot(month, country, metric1, metric2) values ('01-jan-2013', 'usa','100','75');
insert into my_table_for_pivot(month, country, metric1, metric2) values ('01-jan-2013', 'argentina','24','10');
insert into my_table_for_pivot(month, country, metric1, metric2) values ('01-mar-2013', 'brazil','60','15');
insert into my_table_for_pivot(month, country, metric1, metric2) values ('01-feb-2013', 'usa','111','90');
insert into my_table_for_pivot(month, country, metric1, metric2) values ('01-feb-2013', 'argentina','15','20');
insert into my_table_for_pivot(month, country, metric1, metric2) values ('01-feb-2013', 'brazil','75','30');
insert into my_table_for_pivot(month, country, metric1, metric2) values ('01-mar-2013', 'usa','105','70');
insert into my_table_for_pivot(month, country, metric1, metric2) values ('01-mar-2013', 'argentina','27','23');
insert into my_table_for_pivot(month, country, metric1, metric2) values ('01-mar-2013', 'brazil','53,'28');

我的目标是对表进行透视,使月份位于列标题上,但每个指标都列在自己的行上。 我的用户将在下拉列表中选择国家/地区,结果将根据项目下拉列表重新计算(如 :p 20_country) 生成的表看起来像这样......

用户选择美国

Metric  jan13  feb13 mar13
metric1 100     111   105
metric2 75      90    70 

我的透视尝试没有奏效,因为我不知道如何在行级别获取指标名称。

select *
from (
select
country,
month,
metric1,
metric2
from my_table_for_pivot)
pivot (
sum(metric1) as mo1,sum(metric2) as mo2 for month IN
('01-JAN-14' AS JAN_14,
 '01-FEB-14' AS FEB_14,
 '01-MAR-14' AS MAR_14))
where country = 'usa'
;

我确实尝试使用SQLfiddle,但无法为此示例工作。非常感谢任何帮助或建议。

我很确定有更优化的方法来编写此查询,但这是一种方法; 将指标值合并到单个列中,并添加一个在透视部分中未提及的名称列。这将为每个名称创建一行;

SELECT *
FROM (
  SELECT country, month, metric1 metric, 'metric1' metric_name
  FROM my_table_for_pivot
  UNION ALL
  SELECT country, month, metric2 metric, 'metric2' metric_name
  FROM my_table_for_pivot
)
PIVOT (
  SUM(metric) as month for month IN
('01-JAN-2013' AS JAN_13,
 '01-FEB-2013' AS FEB_13,
 '01-MAR-2013' AS MAR_13))
WHERE country = 'usa'
;

用于测试的 SQL小提琴。

最新更新