带有多个sum列的Oracle SQL PIVOT

时间:2014-03-05 19:47:33

标签: sql oracle 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');

我的目标是透视表,以便月份沿列标题,但每个指标都列在自己的行上。我的用户将在下拉列表中选择国家/地区,结果将根据项目下拉列表重新计算(例如:p20_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但是无法为这个例子工作..非常感谢任何帮助或建议。

1 个答案:

答案 0 :(得分:2)

我很确定有更多最佳方式来编写此查询,但这是一种方法;将度量标准值合并到一个列中,并添加一个名称列,该列在枢轴部分中未提及。这将为每个名称创建一行;

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'
;

An SQLfiddle to test with