2009-12-14 40 views
2

我有一個名爲Item Item的列ItemID(PK),ItemName,ExpectedSubItems和另一個名爲SubItem與列SubItemID(PK),ItemID(FK),SubItemName的表。SQL的返回行的子項的計數不等於列值

我想返回Item中的所有行,其中SubItems的數量與ExpectedSubItems不同。

我嘗試使用類似: -

Select * From Item 
Join SubItem on Item.ItemID = SubItem.ItemID 
Where ExpectedSubItems = Count(SubItem.ItemID) 

但給我的錯誤: -

An aggregate may not appear in the WHERE clause unless it is in a subquery contained in a HAVING clause or a select list, and the column being aggregated is an outer reference.

任何想法從SQL大師的在那裏?

回答

3

你需要一個子查詢

select * 
    from item 
    where expectedsubtems <> (
    select count(*) 
     from subitem 
     where subitem.itemid = item.itemid 
    ) 
1

嘗試:

Select i.ItemId, i.ItemName 
From Item i 
    Left Join SubItem s 
    On s.ItemID = i.ItemId 
Group By i.ItemId, i.ItemName, i.ExpectedSubItems 
Having Count(*) <> i.ExpectedSubitems 
+0

你需要一個GROUP BY在某處有 – 2009-12-14 16:32:29

+0

天哪,這個論壇是快... – 2009-12-14 16:32:57

+0

是的,我相信一些響應者實際上是監控論壇24小時的機器人,並立即回答任何問題:) – 2009-12-14 16:35:20

1

這應做到:

SELECT 
    I.item_id, 
    I.item_name, 
    I.expected_subitems 
FROM 
    Items I 
LEFT OUTER JOIN Sub_Items SI ON 
    SI.item_id = I.item_id 
GROUP BY 
    I.item_id, 
    I.item_name, 
    I.expected_subitems 
HAVING 
    COUNT(SI.item_id) <> I.expected_subitems 
+1

左外連接也獲得沒有子條目的項目 – 2009-12-14 16:35:08

+0

是的,我只是試圖想出任何簡單的方法,可以避免沒有實際子項目的expected_subitems爲1的問題。 COUNT(*)最終還是會回到1,從而導致誤報。 – 2009-12-14 16:39:35

+0

'Tom H.':你可以使用'COUNT(SubItem.ID)'和'LEFT JOIN'。 – Quassnoi 2009-12-14 16:40:44

1
SELECT ItemID 
FROM Item 
JOIN SubItem 
ON  SubItem.ItemID = Item.ItemID 
GROUP BY 
     ItemID, ExpectedSubItems 
HAVING ExpectedSubItems <> COUNT(*) 

或這(讓你不必須由所有Item字段組成,並且也是工程預計0子項)

SELECT Item.* 
FROM Item 
CROSS APPLY 
     (
     SELECT NULL 
     FROM SubItem 
     WHERE SubItem.ItemID = Item.ItemID 
     HAVING ExpectedSubItems <> COUNT(*) 
     ) S 
0

嘗試以下操作:

select * 
    from Item I 
    LEFT OUTER JOIN (select ItemID, COUNT(*) as ActualSubItemCount 
        from SubItem 
        group by ItemID) S 
    ON (I.ItemID = S.ItemID) 
    where (S.ItemID IS NULL AND NVL(I.ExpectedSubItems, 0) <> 0) OR 
     I.ExpectedSubItems <> S.ActualSubItemCount;