应该相当简单,但我是SQL的新手,无法让它工作:
Table 1:
ID Qty
ItemA 3
ItemB 5
ItemD 2
Table 2:
ID Qty
ItemC -1
ItemB 1.5
ItemE 2.2
我只想要一张表格,其数量与ID相加。
答案 0 :(得分:0)
这样的事情:
SELECT ID, SUM(Qty) SumQty
FROM
(
SELECT ID, Qty FROM Table1
UNION ALL
SELECT ID, Qty FROM Table2
) A
GROUP BY ID
答案 1 :(得分:0)
这将按{ID:
对Qty
字段和组进行求和
SELECT
a.ID AS id,
(SUM(a.Qty) + SUM(b.Qty)) as qty_sum
FROM
[Table 1] as a
JOIN
[Table 2] as b ON (a.ID = b.ID)
GROUP BY 1;
您应从此示例中获取的关键部分是:
JOIN
这就是你连接两个表的方式。请注意,它通过`ON(a.ID = b.ID)SUM
功能获取总计。GROUP BY
群组...... 答案 2 :(得分:0)
与@patsweet类似,但使用INNER JOIN并且格式更容易阅读
SELECT SUM(t1.Qty + t1.Qty) AS TotalQty ,
t1.ID
FROM [Table 1] t1
INNER JOIN [Table 2] t2 WITH (NOLOCK) ON t2.ID = t1.ID
GROUP BY t1.ID