postgresql - 如何在 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
解决方案
选项 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 上的下一个与数据库查询相关的问题也这样做:-)
推荐阅读
- c - 制作一个查找位数的函数
- python - 即使路径正确,Selenium 也会通过 xpath 显示错误的元素
- java - Spring JPA 规范 - 生成纯 SQL Where-Clause
- scipy-optimize-minimize - 带有约束的 scipy.optimize.minimize 不能按预期工作
- arrays - 最坏情况下的大 omega(n) 是什么意思?
- node.js - npx create-express-api 不断收到未知错误
- kubernetes - Kubernetes pvc 请求和物理存储
- android - Apps 脚本无法通过 Flutter App APK 访问
- c# - 如何使用服务器端 ASP.NET Core 3.1 MVC 访问浏览器的本地存储
- r - 预处理数据后如何在 tidymodels R 中进行预测