oracle pivot 中的列
Posted
技术标签:
【中文标题】oracle pivot 中的列【英文标题】:columns in oracle pivot 【发布时间】:2011-10-19 05:06:58 【问题描述】:示例选择:
select *
from (
select 1 cnt, 2 sm, '55' name, 12 month, 2011 year, '12 2011' mnth_txt from dual union all
select 1 cnt, 2 sm, '54' name, 11 month, 2011 year, '11 2011' mnth_txt from dual union all
select 1 cnt, 2 sm, '55' name, 11 month, 2011 year, '11 2011' mnth_txt from dual union all
select 1 cnt, 2 sm, '54' name, 12 month, 2011 year, '12 2011' mnth_txt from dual union all
select 1 cnt, 2 sm, '55' name, 12 month, 2011 year, '12 2011' mnth_txt from dual union all
select 1 cnt, 2 sm, '56' name, 12 month, 2010 year, '12 2010' mnth_txt from dual
) pivot (
sum(cnt) cnt, sum(sm) sm
for name in
( '55' as "Omsk"
, '54' as "Novosibirsk"
, '56' as "Orenburg"
)
)
输出:
|month| year | mnth_txt |Omsk_cnt|Omsk_sm|Novosibirsk_cnt|Novosibirsk_sm|Orenburg_cnt| Orenburg_sm|
| 12 | 2010 |'12 2010' | (null) | (null)| (null) | (null) | 1 | 2 |
| 12 | 2011 |'12 2011' | 2 | 4 | 1 | 2 | (null) | (null) |
| 11 | 2011 |'11 2011' | 1 | 2 | 1 | 2 | (null) | (null) |
是否可以按时间顺序对记录进行排序,不包括“月”和“年”列? 不列出所有列。
UPD
需要:
| mnth_txt |Omsk_cnt|Omsk_sm|Novosibirsk_cnt|Novosibirsk_sm|Orenburg_cnt| Orenburg_sm|
|'12 2010' | (null) | (null)| (null) | (null) | 1 | 2 |
|'11 2011' | 1 | 2 | 1 | 2 | (null) | (null) |
|'12 2011' | 2 | 4 | 1 | 2 | (null) | (null) |
类似:
select mnth_txt, pivoted_columns.*
【问题讨论】:
【参考方案1】:要对记录进行排序,您可以在 sql 末尾添加以下内容
ORDER BY TO_DATE('01/'||month||'/'||year,'dd/mm/yyyy')
注意:透视列名称区分大小写,因此您需要引用它们
这是完整的查询,只选择您需要的列:
SELECT mnth_txt,"Omsk_CNT","Omsk_SM","Novosibirsk_CNT",
"Novosibirsk_SM","Orenburg_CNT","Orenburg_SM"
FROM
(
SELECT *
FROM (
SELECT 1 cnt, 2 sm, '55' name, 12 month, 2011 year, '12 2011' mnth_txt FROM DUAL UNION ALL
SELECT 1 cnt, 2 sm, '54' name, 11 month, 2011 year, '11 2011' mnth_txt FROM DUAL UNION ALL
SELECT 1 cnt, 2 sm, '55' name, 11 month, 2011 year, '11 2011' mnth_txt FROM DUAL UNION ALL
SELECT 1 cnt, 2 sm, '54' name, 12 month, 2011 year, '12 2011' mnth_txt FROM DUAL UNION ALL
SELECT 1 cnt, 2 sm, '55' name, 12 month, 2011 year, '12 2011' mnth_txt FROM DUAL UNION ALL
SELECT 1 cnt, 2 sm, '56' name, 12 month, 2010 year, '12 2010' mnth_txt FROM DUAL )
PIVOT ( SUM(cnt) cnt, SUM(sm) sm
FOR NAME IN
( '55' AS "Omsk",'54' AS "Novosibirsk", '56' AS "Orenburg" )
)
ORDER BY TO_DATE('01/'||month||'/'||year,'dd/mm/yyyy')
)
【讨论】:
我不知道如何从选定的文件中排除这 2 列 我有 15 个名字和 3 个聚合。需要直接列出所有列吗? 不幸的是,你需要把它们都列出来以上是关于oracle pivot 中的列的主要内容,如果未能解决你的问题,请参考以下文章
PIVOT在SQL Sever里面和Oracle里面的用法区别