這裏是我的嘗試......
declare @Depatments table
(
DeptID int
,DeptName varchar(15)
)
declare @Groups table
(
GroupID int
,DeptID int
)
declare @Inventory table
(
ItemID int
,GroupID int
)
INSERT INTO @Depatments VALUES (1,'Department 1')
INSERT INTO @Depatments VALUES (2,'Department 2')
INSERT INTO @Depatments VALUES (3,'Department 3')
INSERT INTO @Depatments VALUES (4,'Department 4')
INSERT INTO @Groups VALUES (1,1)
INSERT INTO @Groups VALUES (2,1)
INSERT INTO @Groups VALUES (3,3)
INSERT INTO @Groups VALUES (4,4)
INSERT INTO @Groups VALUES (5,2)
INSERT INTO @Groups VALUES (6,3)
INSERT INTO @Groups VALUES (7,1)
INSERT INTO @Groups VALUES (8,3)
INSERT INTO @Inventory VALUES (1 ,2)
INSERT INTO @Inventory VALUES (2 ,3)
INSERT INTO @Inventory VALUES (3 ,8)
INSERT INTO @Inventory VALUES (4 ,1)
INSERT INTO @Inventory VALUES (5 ,4)
INSERT INTO @Inventory VALUES (6 ,5)
INSERT INTO @Inventory VALUES (7 ,1)
INSERT INTO @Inventory VALUES (8 ,2)
INSERT INTO @Inventory VALUES (9 ,2)
INSERT INTO @Inventory VALUES (10,3)
INSERT INTO @Inventory VALUES (11,7)
--works with derived tables
SELECT
d.DeptName,dt_g.CountOf AS GroupCount, dt_i.CountOf AS InventotyCount
FROM @Depatments d
LEFT OUTER JOIN (SELECT
COUNT(*) AS CountOf,DeptID
FROM @Groups
GROUP BY DeptID
) dt_g ON d.DeptID=dt_g.DeptID
LEFT OUTER JOIN (SELECT
COUNT(*) AS CountOf,g.DeptID
FROM @Groups g
INNER JOIN @Inventory i ON g.GroupID=i.GroupID
GROUP BY DeptID
) dt_i ON d.DeptID=dt_i.DeptID
@Lieven:感謝您的標籤編輯。我很習慣在2005年工作,標籤已成爲本能。 – TheTXI 2009-04-09 13:57:23
@TheTXI:不要提及它。順便說一句,我相信部門2的團隊人數和itemcount應該是1?! – 2009-04-09 14:06:37
部門2爲什麼組計數爲0? – Quassnoi 2009-04-09 14:07:16