gpt4 book ai didi

sql - oracle pivot 中的列

转载 作者:行者123 更新时间:2023-12-05 01:30:20 25 4
gpt4 key购买 nike

示例选择:

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.*

最佳答案

要对记录进行排序,您可以将以下内容添加到 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')
)

关于sql - oracle pivot 中的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7816771/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com