Sql Join和Sum

时间:2014-10-09 18:49:33

标签: sql join

我正在尝试使用左连接从两个不同的表中总计一个数量。无论第二个表是否匹配,我都需要返回所有行。

   SELECT l.tender, 
          l.starting+SUM(t.amount) AS 'amount' 
     FROM label l 
LEFT JOIN transfers t on l.tender=t.name 
 ORDER BY l.tender

2 个答案:

答案 0 :(得分:5)

这应该有效:

SELECT  l.tender, 
        l.starting + ISNULL(t.amount,0) AS amount
FROM label l 
LEFT JOIN ( SELECT name, SUM(amount) amount
            FROM transfers
            GROUP BY name) t 
    ON l.tender = t.name 
ORDER BY l.tender

答案 1 :(得分:2)

SUM(amount)包裹在COALESCE函数中,这样如果没有匹配且为NULL,则会添加0并且不会标记整行为NULL

将查询的第2行更改为:

      l.starting + COALESCE(SUM(t.amount), 0) AS amount

编辑:

正如@Lamak所说,您还需要GROUP BY您的结果,以便{J}正确地SUM。整个查询看起来像这样(替代其他答案):

   SELECT l.tender, 
          l.starting + COALESCE(SUM(t.amount), 0) AS amount 
     FROM label l 
LEFT JOIN transfers t on l.tender=t.name 
GROUP BY l.tender, l.starting
ORDER BY l.tender