[英]Eliminate zero values and put values in two different columns in one row
CREATE TABLE check_inbound
(
id SERIAL PRIMARY KEY,
data_source VARCHAR,
product VARCHAR,
inbound_type VARCHAR,
quantity DECIMAL
);
INSERT INTO check_inbound (data_source, product, inbound_type, quantity)
VALUES
('data_source_01', 'product_a', 'type_01', '500'),
('data_source_01', 'product_a', 'type_02', '200'),
('data_source_01', 'product_b', 'type_01', '130'),
('data_source_01', 'product_b', 'type_02', '320'),
('data_source_01', 'product_c', 'type_01', '700'),
('data_source_01', 'product_c', 'type_02', '850'),
('data_source_02', 'product_a', 'type_01', '980'),
('data_source_02', 'product_a', 'type_02', '315'),
('data_source_02', 'product_b', 'type_01', '760'),
('data_source_02', 'product_b', 'type_02', '512'),
('data_source_02', 'product_c', 'type_01', '125'),
('data_source_02', 'product_c', 'type_02', '720');
Expected result:预期结果:
product![]() |
inbound_type![]() |
quantity_data_source_01![]() |
quantity_data_source_02![]() |
---|---|---|---|
product_a![]() |
type_01 ![]() |
500 ![]() |
980 ![]() |
product_a![]() |
type_02 ![]() |
200 ![]() |
315 ![]() |
product_b![]() |
type_01 ![]() |
130 ![]() |
760 ![]() |
product_b![]() |
type_02 ![]() |
320 ![]() |
512 ![]() |
product_c![]() |
type_01 ![]() |
700 ![]() |
125 ![]() |
product_c![]() |
type_02 ![]() |
850 ![]() |
720 ![]() |
I want to compare the quantity
per product
and inbound_type
in two different data_sources
.我想比较两个不同
data_sources
中每个product
和inbound_type
的quantity
。
I was able to come close to the result with this query:我能够通过这个查询接近结果:
SELECT
i.data_source AS date_source,
i.product AS product,
i.inbound_type AS inbound_type,
(CASE WHEN i.data_source = 'data_source_01' THEN SUM(i.quantity) ELSE 0 END) AS quantity_data_source_01,
(CASE WHEN i.data_source = 'data_source_02' THEN SUM(i.quantity) ELSE 0 END) AS quantity_data_source_02
FROM
check_inbound i
GROUP BY
1, 2, 3
ORDER BY 2,1
However, I could not figure out how I can get rid of the rows with the zero values and put the quantities on the same line as in the expected result.但是,我无法弄清楚如何摆脱具有零值的行并将数量放在与预期结果相同的行上。
Do you have any idea what I need to change to make it work?你知道我需要改变什么才能让它工作吗?
You are doing a pivot query here, and should be aggregating only by product and type.您在此处执行 pivot 查询,并且应该仅按产品和类型进行聚合。 I suggest using
MAX
with FILTER
here:我建议在这里使用
MAX
和FILTER
:
SELECT
i.product AS product,
i.inbound_type AS inbound_type,
MAX(i.quantity) FILTER (WHERE i.data_source = 'data_source_01') AS quantity_data_source_01,
MAX(i.quantity) FILTER (WHERE i.data_source = 'data_source_02') AS quantity_data_source_02
FROM check_inbound i
GROUP BY 1, 2
ORDER BY 2, 1;
If you wanted to use CASE
expressions, then use this version eg如果您想使用
CASE
表达式,请使用此版本,例如
MAX(CASE WHEN i.data_source = 'data_source_01'
THEN i.quantity END) AS quantity_data_source_01
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.