Oracle SQL 数据透视查询
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4841718/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Oracle SQL pivot query
提问by code990
I have data in a table as seen below:
我在表中有数据,如下所示:
MONTH VALUE
1 100
2 200
3 300
4 400
5 500
6 600
I want to write a SQL query so that result is given as below:
我想编写一个 SQL 查询,以便给出如下结果:
MONTH_JAN MONTH_FEB MONTH_MAR MONTH_APR MONTH_MAY MONTH_JUN
100 200 300 400 500 600
回答by René Nyffenegger
Oracle 11g and above
Oracle 11g 及以上
As of Oracle 11g, you can now use the PIVOT
operator to achieve that result:
从 Oracle 11g 开始,您现在可以使用PIVOT
运算符来实现该结果:
create table tq84_pivot (
month number,
value number
);
insert into tq84_pivot values(1, 100);
insert into tq84_pivot values(2, 200);
insert into tq84_pivot values(3, 300);
insert into tq84_pivot values(4, 400);
insert into tq84_pivot values(5, 500);
insert into tq84_pivot values(6, 600);
--
insert into tq84_pivot values(1, 400);
insert into tq84_pivot values(2, 350);
insert into tq84_pivot values(4, 150);
select
*
from
tq84_pivot
pivot (
sum (value) as sum_value for
(month) in (1 as month_jan,
2 as month_feb,
3 as month_mar,
4 as month_apr,
5 as month_mai,
6 as month_jun,
7 as month_jul,
8 as month_aug,
9 as month_sep,
10 as month_oct,
11 as month_nov,
12 as month_dec)
);
回答by OMG Ponies
Oracle 9i+ supports:
Oracle 9i+ 支持:
SELECT SUM(CASE WHEN t.month = 1 THEN t.value ELSE 0 END) AS JAN,
SUM(CASE WHEN t.month = 2 THEN t.value ELSE 0 END) AS FEB,
SUM(CASE WHEN t.month = 3 THEN t.value ELSE 0 END) AS MAR,
SUM(CASE WHEN t.month = 4 THEN t.value ELSE 0 END) AS APR,
SUM(CASE WHEN t.month = 5 THEN t.value ELSE 0 END) AS MAY,
SUM(CASE WHEN t.month = 6 THEN t.value ELSE 0 END) AS JUN
FROM YOUR_TABLE t
You only list two columns -- something like this should probably be grouped by year.
你只列出两列——像这样的东西可能应该按年份分组。
There is ANSI PIVOT (and UNPIVOT) syntax, but Oracle didn't support it until 11g. Prior to 9i, you'd have to replace the CASE statements with Oracle specific DECODE.
有 ANSI PIVOT(和 UNPIVOT)语法,但 Oracle 直到 11g 才支持它。在 9i 之前,您必须用 Oracle 特定的 DECODE 替换 CASE 语句。