sql - 如何使用 group by 子句在 2 个不同的表列之间进行乘法运算?

标签 sql postgresql

我试了一整天,但没有得到结果。请浏览以下链接中的图片

Here is my table 1 structure

and here is my table 2 structure

我想将第一个表中的 product_uom_qty 与第二个表中的成本相乘,然后按 product_id 对它们进行分组,这是两个表。

这是我的查询。

select sum(sale_order_line.product_uom_qty) * product_price_history.cost 
from sale_order_line, product_price_history
group by product_id;

我得到的结果是

ERROR: column reference "product_id" is ambiguous. LINE 1: ...m sale_order_line, product_price_history group by product_id...

请告诉我哪里出错了。

最佳答案

大概,你想要这样的东西:

select product_id, sum(sol.product_uom_qty * pph.cost)
from sale_order_line sol join
     product_price_history pph
     using (product_id)
group by product_id;

也就是说,你需要在某些条件下加入表格。

如果没有样本数据和预期结果,就不清楚您真正想要什么。但这至少是一个删除语法错误的明智查询。

关于sql - 如何使用 group by 子句在 2 个不同的表列之间进行乘法运算?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54617466/

相关文章:

sql - 如何在 Spring bean 中执行 PL/pgSQL 脚本?

mysql - 两个左连接给我不真实的数据(双重数据?)与 MySQL

postgresql - 使用 PostgreSQL 计算相关系数?

python - Django 查询格式化日期时间输出

PHP/MySQL : Adding records based on foreign keys

sql - (通用表表达式)CTE 作为 WHERE 子句的一部分......可能吗?

具有特定基数的 sql 查询(多对多)

postgresql 根据其他列的值计算列的最小值

postgresql - 创建 : database creation failed: ERROR: permission denied to create database

sql - 存储库 - 在 native 查询中排序不起作用