我有3张桌子
表1和表2都通过“ ItemId”外键与表3关联
我想编写一个查询,该查询将基于这些表返回一些统计数据
表3提供了name列,其余部分来自其他两个
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
我在哪里将其放在单个查询中?
答案 0 :(得分: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
答案 1 :(得分:0)
计算外部SELECT
中的其他列,并使用AS
为它们添加别名:
SELECT t1.ItemId,
name,
currentQuantity,
previousQuantity,
currentValue,
previousValue,
currentQuantity - previousQuantity as qDiff,
currentValue - previousValue as valDiff
FROM ....