Oracle SQL中的双透视

taor4pac  于 2023-11-17  发布在  Oracle
关注(0)|答案(1)|浏览(103)

我有下面的一组数据,我试图做一个交叉表/双枢轴。不知道最好的描述。我想做的是把每个产品(列a)在接下来的2列(b和c)与列D的值相加。
Left Side is current raw data - Right is End Goal
我尝试创建一些枢轴,但无法实现我的最终结果

z2acfund

z2acfund1#

只需PIVOT一次,然后将值相加即可获得总数:

SELECT product_name,
       COALESCE(gross_cdc, 0) AS gross_cdc,
       COALESCE(gross_other, 0) AS gross_other,
       COALESCE(returns_cdc, 0) AS returns_cdc,
       COALESCE(returns_other, 0) AS returns_other,
       COALESCE(gross_cdc, 0)
         + COALESCE(gross_other, 0)
         + COALESCE(returns_cdc, 0)
         + COALESCE(returns_other, 0) AS total
FROM   table_name
PIVOT (
  SUM(doses)
  FOR (sales_category, sales_type) IN (
    ('CDC',   'GROSS')   AS gross_cdc,
    ('OTHER', 'GROSS')   AS gross_other,
    ('CDC',   'RETURNS') AS returns_cdc,
    ('OTHER', 'RETURNS') AS returns_other
  )
)

字符串
其中,对于样本数据:

CREATE TABLE table_name (product_name, sales_category, sales_type, doses) AS
  SELECT 'Product1', 'OTHER', 'GROSS',    15 FROM DUAL UNION ALL
  SELECT 'Product1', 'OTHER', 'RETURNS',  -5 FROM DUAL UNION ALL
  SELECT 'Product2', 'CDC',   'GROSS',    20 FROM DUAL UNION ALL
  SELECT 'Product2', 'OTHER', 'GROSS',    25 FROM DUAL UNION ALL
  SELECT 'Product2', 'OTHER', 'RETURNS',  -5 FROM DUAL UNION ALL
  SELECT 'Product3', 'CDC',   'GROSS',    30 FROM DUAL UNION ALL
  SELECT 'Product3', 'OTHER', 'GROSS',    25 FROM DUAL UNION ALL
  SELECT 'Product3', 'OTHER', 'RETURNS', -10 FROM DUAL;


产出:
| 产品名称|毛_CDC|毛额_其他|退货_CDC|退货_其他|总|
| --|--|--|--|--|--|
| Product1| 0 | 15 | 0 |-5| 10 |
| Product2| 20 | 25 | 0 |-5| 40 |
| 产品3| 30 | 25 | 0 |-10| 45 |
fiddle

相关问题