选择可以存在于多个表中的不同项目总和

时间:2015-04-30 08:23:28

标签: sqlite

假设我有3个表:Article1,Articles2,Articles3。

两个theese表中可能存在相同的文章组。 我只想按第1条中存在的每个文章组加总金额,而在其他表格中不存在。

表格

Articles1

| Id    |    ArticleName    |    Amount |
-----------------------------------------
  '1'         'Apple'              '2'
  '2'         'Orange'             '2'
  '3'         'Banana'             '3'

Articles2

| Id    |    ArticleName    |    Amount |
-----------------------------------------
  '1'         'Apple'              '2'
  '2'         'Orange'             '2'

Articles3

| Id    |    ArticleName    |    Amount |
-----------------------------------------
  '1'         'Apple'              '2'
  '2'         'Orange'             '2'

我的代码:

SELECT SUM(a1.Amount) 
FROM Articles1 a1
LEFT OUTER JOIN Articles2 a2
   ON a1.Id = a2.Id
LEFT OUTER JOIN Articles3 a3
   ON a1.Id = a3.Id
WHERE a1.Id <> a2.Id OR a1.Id <> a3.Id
GROUP BY a1.ArticleName

Fiddle

1 个答案:

答案 0 :(得分:1)

将您的查询修改为

select sum(a1.Amount)
FROM Articles1 a1
WHERE 
a1.Id not in (select Id from Articles2) and 
a1.Id not in (select Id from Articles3)
GROUP BY a1.ArticleName

这将返回3作为输出,即仅适用于香蕉。

Fiddle