[英]SQL return rows where count of children does not equal column value
I have a table called Item with columns ItemID (PK), ItemName, ExpectedSubItems and another table called SubItem with columns SubItemID (PK), ItemID (FK), SubItemName. 我有一个名为Item的表,其列为ItemID(PK),ItemName,ExpectedSubItems,另一个表为SubItem,其表为SubItemID(PK),ItemID(FK),SubItemName列。
I want to return all rows from Item where the number of SubItems is different from ExpectedSubItems. 我想从Item返回所有行,其中SubItems的数量与ExpectedSubItems不同。
I tried to use something like:- 我试图使用类似:
Select * From Item
Join SubItem on Item.ItemID = SubItem.ItemID
Where ExpectedSubItems = Count(SubItem.ItemID)
but that gives me the error:- 但这给了我错误:-
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.
除非聚集在HAVING子句或选择列表中包含的子查询中,并且聚集的列是外部引用,否则聚集可能不会出现在WHERE子句中。
Any ideas from the SQL guru's out there? SQL专家有什么想法吗?
you need a sub-query 您需要一个子查询
select *
from item
where expectedsubtems <> (
select count(*)
from subitem
where subitem.itemid = item.itemid
)
try: 尝试:
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
This should do it: 应该这样做:
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
SELECT ItemID
FROM Item
JOIN SubItem
ON SubItem.ItemID = Item.ItemID
GROUP BY
ItemID, ExpectedSubItems
HAVING ExpectedSubItems <> COUNT(*)
or this (so that you don't have to group by all Item
fields and which also works for 0
expected subitems) 或这个(这样您就不必按所有“
Item
字段分组,并且也适用于0
预期的子项目)
SELECT Item.*
FROM Item
CROSS APPLY
(
SELECT NULL
FROM SubItem
WHERE SubItem.ItemID = Item.ItemID
HAVING ExpectedSubItems <> COUNT(*)
) S
Try the following: 请尝试以下操作:
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.