代码之家  ›  专栏  ›  技术社区  ›  Christopher Edwards

SQL返回子级计数不等于列值的行

  •  2
  • Christopher Edwards  · 技术社区  · 15 年前

    我有一个名为item的表,其中列有itemid(pk)、itemname、expectedsubitems,另一个名为subitem的表,其中列有subitemid(pk)、itemid(fk)、subitemname。

    如果子项的数目与预期子项的数目不同,则返回该项的所有行。

    我试着用类似的东西:

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

    但这给了我一个错误:

    集合不能出现在 WHERE子句,除非它位于 HAVING子句中包含的子查询 或选择列表,列 聚合是一个外部引用。

    SQL专家有什么想法吗?

    5 回复  |  直到 15 年前
        1
  •  3
  •   Ray    15 年前

    您需要子查询

    select *
      from item
      where expectedsubtems <> (
        select count(*)
          from subitem
          where subitem.itemid = item.itemid
        )
    
        2
  •  1
  •   Charles Bretana    15 年前

    尝试:

    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
    
        3
  •  1
  •   Quassnoi    15 年前
    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
  •  1
  •   Tom H    15 年前

    应该这样做:

    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
    
        5
  •  0
  •   Bob Jarvis - Слава Україні    15 年前

    尝试以下操作:

    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;