简体   繁体   English

Oracle SQL - 将多行转为单列

[英]Oracle SQL - Pivoting multiple rows into single column

To all the Oracle SQL pros, please, I'm trying to use a pivot to convert multiple rows into a single column.对于所有 Oracle SQL 专家,我正在尝试使用数据透视将多行转换为单列。 I tried looking through past posting but could not find anything related to what I want to do, or maybe I just don't know how to search for it properly.我尝试查看过去的帖子,但找不到与我想做的事情相关的任何内容,或者我只是不知道如何正确搜索它。 I want to take the rows HAND, PECO, CHEP and make that into 1 column called EXTRA, while leaving STORAGE and RENEWAL as their own separate columns.我想将 HAND、PECO、CHEP 行放入名为 EXTRA 的 1 列中,同时将 STORAGE 和 RENEWAL 作为它们自己的单独列。 I'm stumped, any help would be greatly appreciated.我很难过,任何帮助将不胜感激。 Thanks in advance!提前致谢!

My current sql is,我目前的 sql 是,

select * from (
select company, customer, rev_code, sum(rev_amt) amt
from revenue_anal
where company='01'
and rev_date between to_date('20\01\01','YY\MM\DD') and sysdate
group by company, customer, rev_code
order by 2,1 )
pivot (sum(amt) for rev_code in ('HAND', 'PECO', 'CHEP', 'STORAGE', 'RENEWAL'))

Query, 

COMPANY | CUSTOMER  | REV_CODE  | REV_AMT
---------------------------------------------------
01  | 101962    | HAND      | 253.377
01  | 101962    | PECO      | 60
01  | 101962    | CHEP      | 1632
01  | 101962    | STORAGE   | 2700
01  | 101962    | RENEWAL   | 60
---------------------------------------------------

Output with my current query,

COMPANY | CUSTOMER  | HAND      | PECO  | CHEP  | STORAGE   | RENEWAL
--------------------------------------------------------------------------
01      | 101962    | 253.377   | 60    | 1632  | 2700      | 60


Trying to get the output to show as 

COMPANY | CUSTOMER  | EXTRA     | STORAGE   | RENEWAL
------------------------------------------------------------------
01      | 101962    | 1945.377  | 2700      | 60

Thank you for taking the time to assist.感谢您抽出宝贵时间提供帮助。

Instead of select * from ( at the very beginning of your query, write而不是select * from (在查询的最开始,写

select company, customer, hand + peco + chep as extra, storage, renewal
from   (
.........

If you expect that any of HAND , PECO or CHEP may be NULL , wrap each of them individually within NVL(...., 0) (if, in fact, NULL is to be interpreted as zero; otherwise, leave as is, and the result will be NULL if at least one of the terms is NULL ).如果您希望HANDPECOCHEP中的任何一个可能为NULL ,请将它们中的每一个单独包装在NVL(...., 0) (如果实际上NULL将被解释为零;否则,保持原样,如果至少有一项为NULL则结果将为NULL )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM