2009-12-14 37 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;