2012-05-11 148 views
2

我有一個父/子/孫類型的表關係定義如下得到計數數據:子查詢中使用查詢值從另一個表

表A: 的parentID 描述

tableB的: childID的 parentId的 描述

表C: grandchildID childID的 描述 項目完成

我需要編寫一個查詢,它將列出tableB中任何給定parentID的所有記錄,以及grandchild記錄的總數和已完成的grandchild記錄的總數(其中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以獲取項目數量和項目數量?

回答

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 
+0

謝謝了!完美的作品。 +1替代,更好的建議與左外連接。 –

相關問題