我请求您的合作,因为pivot
在表上并用null
分隔记录,但仍将字段NVL
保留为0
表
product | value
----------+-------
Shirts | 1200
Caps | 0
Stocks | 0
Glasses | 100
Shoes | 0
Código支点
select * from products
PIVOT (sum(value)
for titles in ('product', 'value')) AS pivot_product
结果:
product | Shirts | Caps | Stocks | Glasses | Shoes
---------+-----------+--------+-------------+---------+----------
value | NULL | NULL | NULL | 100 | NULL
value | 1200 | NULL | NULL | NULL | NULL
预期结果:
product | Shirts | Caps | Stocks | Glasses | Shoes
---------+-----------+--------+-------------+-------+----------
valor | 1200 | NULL | NULL | 100 | NULL
可选
product | Shirts | Caps | Stocks | Glasses | Shoes
---------+-----------+--------+-------------+-------+----------
valor | 1200 | 0 | 0 | 100 | 0
答案 0 :(得分:2)
您需要将列值放在数据透视表中:
Oracle设置:
CREATE TABLE test_data ( product, value ) AS
SELECT 'Shirts', 1200 FROM DUAL UNION ALL
SELECT 'Caps', 0 FROM DUAL UNION ALL
SELECT 'Stocks', 0 FROM DUAL UNION ALL
SELECT 'Glasses', 100 FROM DUAL UNION ALL
SELECT 'Shoes', 0 FROM DUAL
查询:
SELECT 'value' AS product,
p.*
FROM test_data
PIVOT ( SUM( value ) FOR product IN (
'Shirts' AS Shirts,
'Caps' AS Caps,
'Stocks' AS Stocks,
'Glasses' AS Glasses,
'Shoes' AS Shoes
) ) p
输出:
PRODUCT | SHIRTS | CAPS | STOCKS | GLASSES | SHOES :------ | -----: | ---: | -----: | ------: | ----: value | 1200 | 0 | 0 | 100 | 0
db <>提琴here
答案 1 :(得分:2)
仅使用条件聚合。更加灵活:
select 'valor' as product,
sum(case when product = 'Shirts' then value end) as shirts,
sum(case when product = 'Caps' then value end) as caps,
sum(case when product = 'Stocks' then value end) as stockes,
sum(case when product = 'Shirts' then value end) as shirts,
sum(case when product = 'Glasses' then value end) as glasses,
sum(case when product = 'Shoes' then value end) as shoes
from test_data;