PostgreSQL group by 子句中,如何在特定列中保留一条记录,并使其他记录值为0?
How to keep one record in specific column and make other record value 0 in group by clause in PostgreSQL?
我有这样一组数据
结果应该是这样的
我的查询
SELECT max(pi.pi_serial) AS proforma_invoice_id,
max(mo.manufacturing_order_master_id) AS manufacturing_order_master_id,
max(pi.amount_in_local_currency) AS sales_value,
FROM proforma_invoice pi
JOIN schema_order_map som ON pi.pi_serial = som.pi_id
LEFT JOIN manufacturing_order_master mo ON som.mo_id = mo.manufacturing_order_master_id
WHERE to_date(pi.proforma_invoice_date, 'DD/MM/YYYY') BETWEEN to_date('01/03/2021', 'DD/MM/YYYY') AND to_date('19/04/2021', 'DD/MM/YYYY')
AND pi.pi_serial in (9221,
9299)
GROUP BY mo.manufacturing_order_master_id,
pi.pi_serial
ORDER BY pi.pi_serial
选项 1:在 Crystal 报告中创建一个“运行 总计”字段,以便每个“proforma_invoice_id”仅汇总一个“sales_value”。
选项 2:向您的 Postgresql 查询添加一个辅助列,如下所示:
case
when row_number()
over (partition by proforma_invoice_id
order by manufacturing_order_master_id)
= 1
then sales_value
else 0
end
as sales_value
我为您准备了 this SQLFiddle 示例(当然也希望鼓励您对下一个关于 SO 的数据库查询相关问题做同样的事情:-)
我有这样一组数据
结果应该是这样的
我的查询
SELECT max(pi.pi_serial) AS proforma_invoice_id,
max(mo.manufacturing_order_master_id) AS manufacturing_order_master_id,
max(pi.amount_in_local_currency) AS sales_value,
FROM proforma_invoice pi
JOIN schema_order_map som ON pi.pi_serial = som.pi_id
LEFT JOIN manufacturing_order_master mo ON som.mo_id = mo.manufacturing_order_master_id
WHERE to_date(pi.proforma_invoice_date, 'DD/MM/YYYY') BETWEEN to_date('01/03/2021', 'DD/MM/YYYY') AND to_date('19/04/2021', 'DD/MM/YYYY')
AND pi.pi_serial in (9221,
9299)
GROUP BY mo.manufacturing_order_master_id,
pi.pi_serial
ORDER BY pi.pi_serial
选项 1:在 Crystal 报告中创建一个“运行 总计”字段,以便每个“proforma_invoice_id”仅汇总一个“sales_value”。
选项 2:向您的 Postgresql 查询添加一个辅助列,如下所示:
case
when row_number()
over (partition by proforma_invoice_id
order by manufacturing_order_master_id)
= 1
then sales_value
else 0
end
as sales_value
我为您准备了 this SQLFiddle 示例(当然也希望鼓励您对下一个关于 SO 的数据库查询相关问题做同样的事情:-)