一尘不染

Oracle枢轴中的列

sql

示例选择:

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

阅读 150

收藏
2021-03-08

共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')         
 )
2021-03-08