[英]Using query values in sub-query to get count data from another table
我有一个父/子/孙类型表关系,定义如下:
tableA:parentID描述
tableB:childID parentId描述
tableC:grandchildID childId描述itemComplete
我需要编写一个查询,该查询将列出任何给定parentID的tableB中的所有记录,以及孙记录的总数和已完成的孙记录的总数(其中itemComplete = true)。
parentID将成为where子句的一部分(从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以获取项目数和完成的项目数?
使用subselects是一个选项,但是我更喜欢JOIN
两个表,并使用带有CASE
语句的GROUP BY
子句来获取总数。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.