加入2个表,总和和分组

时间:2014-03-11 21:10:04

标签: sql join group-by sum

应该相当简单,但我是SQL的新手,无法让它工作:

Table 1:
ID        Qty
ItemA     3 
ItemB     5  
ItemD     2 

Table 2:
ID        Qty
ItemC    -1
ItemB    1.5 
ItemE     2.2

我只想要一张表格,其数量与ID相加。

3 个答案:

答案 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;

您应从此示例中获取的关键部分是:

  1. JOIN这就是你连接两个表的方式。请注意,它通过`ON(a.ID = b.ID)
  2. 确保两个表中的ID匹配
  3. 使用SUM功能获取总计。
  4. 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