如何在sql中添加求和值和连接

问题描述 投票:0回答:2

我有3张桌子

表1和表2都与表3的“ItemId”外键相关联

我想编写一个查询,它将根据这些表返回一些统计数据

表3提供了名称列,其余的是来自另外两个

SELECT t1.ItemId, name, currentQuantity, previousQuantity, currentValue, previousValue
FROM (
  SELECT ItemId, SUM(quantity) as currentQuantity, SUM(quantity * purchaseNetPrice) AS currentValue
  FROM table_1
  GROUP BY ItemId
) AS t1
LEFT JOIN (
  SELECT ItemId, SUM(quantity) as previousQuantity, SUM(quantity * purchaseNetPrice) AS previousValue
  FROM table_2
  GROUP BY ItemId
) AS t2 ON t1.ItemId = t2.ItemId
INNER JOIN table_3 ON table_1.ItemId = table_3.ItemId

这将输出

ItemId | name |  currentQuantity  | previousQuantity| currentValue | previousValue
-------+------+-------------------+-----------------+--------------+---------------
 1     |ITEM1 | 4500              | 27000           | 523000       | 3240000       |
 2     |ITEM2 | 5800              | 15000           | 386000       | 2250000       |

这点很好,但我也想计算数量和价值差异

ItemId | name |  currentQuantity  | previousQuantity| currentValue | previousValue | qDiff | valDiff
-------+------+-------------------+-----------------+--------------+---------------
 1     |ITEM1 | 4500              | 27000           | 523000       | 3240000       | diff  | diff
 2     |ITEM2 | 5800              | 15000           | 386000       | 2250000       | diff  | diff

具有以下逻辑:

数量差异 - > currentQuantity - previousQuantity

值差异 - > currentValue - previousValue

我在哪里将它放在一个查询中?

sql postgresql
2个回答
0
投票

计算外部SELECT中的其他列并使用AS对其进行别名来完成工作:

SELECT t1.ItemId, 
       name, 
       currentQuantity, 
       previousQuantity, 
       currentValue, 
       previousValue, 
       currentQuantity - previousQuantity as qDiff, 
       currentValue - previousValue as valDiff 
FROM ....

0
投票

你得到了大部分权利。我会使用子查询因子(WITH AS)来清除代码。

WITH t1_summary as
(
  SELECT ItemId, SUM(quantity) as currentQuantity, SUM(quantity * purchaseNetPrice) AS currentValue
  FROM table_1
  GROUP BY ItemId
),
t2_summary as (SELECT ItemId, SUM(quantity) as previousQuantity, SUM(quantity * purchaseNetPrice) AS previousValue
  FROM table_2
  GROUP BY ItemId
) 
SELECT t3.ItemId, name, currentQuantity, previousQuantity, currentValue, previousValue, currentQuantity - previousQuantity as quantity_difference, currentValue - previousValue as value_difference
from t3,t1_summary,t2_summary
where t1_summary.ItemId = t3.ItemId
and t2_summary.ItemId = t3.ItemId
© www.soinside.com 2019 - 2024. All rights reserved.