我有一个名为Item的表,其中包含ItemID(PK),ItemName,ExpectedSubItems和另一个名为SubItem的表,其中包含SubItemID(PK),ItemID(FK),SubItemName。
我想从Item中返回所有行,其中SubItems的数量与ExpectedSubItems不同。
我尝试使用类似的东西: -
Select * From Item
Join SubItem on Item.ItemID = SubItem.ItemID
Where ExpectedSubItems = Count(SubItem.ItemID)
但这给了我错误: -
聚合可能不会出现在 WHERE子句,除非它在一个 HAVING子句中包含的子查询 或选择列表,列为 聚合是外部参考。
来自SQL大师的任何想法都在那里?
答案 0 :(得分:3)
您需要一个子查询
select *
from item
where expectedsubtems <> (
select count(*)
from subitem
where subitem.itemid = item.itemid
)
答案 1 :(得分: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
答案 2 :(得分: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
答案 3 :(得分: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
答案 4 :(得分: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;