2

我有一个父/子/孙类型表关系定义如下:

表A:父ID描述

tableB: childID parentId 描述

tableC:grandchildID childId 描述 itemComplete

我需要编写一个查询,该查询将列出 tableB 中任何给定 parentID 的所有记录,以及孙记录的总数和已完成的孙记录的总数(其中 itemComplete = true)。

parentID 将成为 where 子句的一部分(select * from tableB where 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 以获取完整的项目数和项目数?

4

1 回答 1

8

使用子选择是一种选择,但我更喜欢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
于 2012-05-11T12:41:29.530 回答