首页 > 解决方案 > 如何在 PostgreSQL 的 group by 子句中保留特定列中的一条记录并使其他记录值为 0?

问题描述

我有一组这样的数据

在此处输入图像描述

结果应该是这样的

在此处输入图像描述

我的查询

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

标签: postgresqlcrystal-reports

解决方案


选项 1:在 Crystal Reports 中创建一个“运行总计”字段,以便每个“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 

我为您准备了这个 SQLFiddle示例(当然也希望鼓励您对 SO 上的下一个与数据库查询相关的问题也这样做:-)


推荐阅读