用于选择另一个表中引用的所有记录的总和的查询

时间:2014-05-08 19:57:27

标签: sql

我有两个表,父表(id,name,child_id)和孩子(id,姓名,号码) - 并非所有父母都可能有孩子而并非所有孩子都有父母。我需要一个查询来选择子表中所有记录的总和,并且还只选择那些具有父项和那些不具有的记录的总和 - 由父表child_id列确定。怎么办呢?

select
  sum(c.number) AS sum AS a,
  sum(all_child_records_that_have_a_parent) AS b,
  sum(all_child_records_that_do not have a parent) AS c /*do not use a-b if possible*/
from
  child c

" all_child_records_that_have_a_parent"是我无法弄清楚的:)

2 个答案:

答案 0 :(得分:2)

all_child_records_that_do没有父母:

SELECT *
  FROM child
 WHERE id NOT IN (SELECT child_id FROM parent)

答案 1 :(得分:1)

您可以从父表中选择不同的子ID,并将它们外部连接到子表。然后检查是否为NULL。

select
  sum(c.number) AS sum_all_c,
  sum(case when x.child_id is not null then c.number end) AS sum_c_with_parent,
  sum(case when x.child_id is null then c.number end) AS sum_c_without_parent
from child c
left outer join (select distinct child_id from parent) x on x.child_id = c.id;