我有一个父/子/孙子类型表关系定义如下:
表A: 的parentID 描述
tableB的: childID的 parentId的 描述
表C: grandchildID childID的 描述 itemComplete
我需要编写一个查询,列出任何给定parentID的tableB中的所有记录,以及孙子记录的总数和已完成的孙子记录的总数(其中itemComplete = true)。
parentID将是where子句的一部分(select * from tableB,其中parentId = x)。我无法弄清楚的问题是如何从tableC获取计数,因为计数取决于childId的当前行值。
换句话说,我需要某种类似的查询:
select description,
(select count (*) from tableC where childId = X) as Items,
(select count (*) from tableC where childId = X And itemComplete = true) as CompleteItems
from tableB where parentId=Y
其中X是tableB中当前行的childId。如何从子查询中的每一行引用childId以获取项目数和项目数?
答案 0 :(得分:7)
使用子选择是一个选项,但我更喜欢JOIN
两个表,并使用GROUP BY
子句使用CASE
语句来获取总数。
SELECT b.description
, COUNT(*) AS Items
, SUM(CASE WHEN c.itemComplete = true THEN 1 ELSE 0 END) AS CompleteItems
FROM tableB b
LEFT OUTER JOIN tableC c ON c.childid = b.childid
WHERE b.parentID = 'Y'
GROUP BY
b.description
如果您坚持使用原始声明,那么所有遗漏的内容都是对外表的引用tableB.childID
select description,
(select count (*) from tableC where childId = tableB.childID) as Items,
(select count (*) from tableC where childId = tableB.childID And itemComplete = true) as CompleteItems
from tableB where parentId=Y
或重新格式化
SELECT description
, (SELECT COUNT(*) FROM tableC WHERE childId = tableB.childID) AS Items,
, (SELECT COUNT(*) FROM tableC WHERE childId = tableB.childID AND itemComplete = true) AS CompleteItems
FROM tableB
WHERE parentId=Y