Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/oracle/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
SQL查询使用具有复杂逻辑的Group by函数_Sql_Oracle - Fatal编程技术网

SQL查询使用具有复杂逻辑的Group by函数

SQL查询使用具有复杂逻辑的Group by函数,sql,oracle,Sql,Oracle,我有一台台式机器。数据如下所示 Item Sub_Item qty XYZ ABC 100 XYZ ABC 80 XYZ PQR 120 DEF KKK 100 DEF KKK 50 DEF LLL 120 DEF

我有一台台式机器。数据如下所示

Item         Sub_Item       qty

XYZ          ABC            100
XYZ          ABC            80
XYZ          PQR            120
DEF          KKK            100
DEF          KKK             50
DEF          LLL            120
DEF          LLL             70
QQQ          DDD            200
PQR          OOO            100
PQR          OOO             60

情况是,我只需要那些记录, 如果项目有两个或多个不同的子项目, 查询应返回子项的总和(数量)的最小值 如果item&sub_item的group by只返回一行,则应选择Negate

上表的查询结果如下

Item         Sub_Item       qty

XYZ          PQR            120
DEF          KKK            150
它应该选择其他记录,因为它们不符合标准。
请帮助我查询。

那么您尝试了什么?那么该项必须有多个子项,但您只想显示其中一个子项?哪一排?第一排从哪里来?这似乎违反了您的规则。如果某个项目的所有子项目分组仅返回一行,会发生什么情况?场景是,我只需要这些记录,其中项目有两个或多个不同的子项目,查询应返回总和(数量)的最小值分组时的子项,如果项和子项的分组方式仅返回一行,则应为负。抛出错误y.groupqty无效标识符,请帮助好的,我忘记在内部查询中选择
x.groupqty
。毕竟我没有你的桌子(也不想创建它),所以我只是把它放在记事本里汉克斯先生。。它起作用了。我只需要在内部查询中添加分组项、子项。。非常感谢您的帮助……)
select
  y.Item,
  y.SubItem,
  y.GroupQty
from  
    ( -- Rank the items by quantity and exclude the items that only have 1 subitem.
    select
      x.Item,
      x.SubItem,
      x.GroupQty,
      dense_rank() over (partition by x.Item order by x.GroupQty) as GroupRank
    from
        ( -- Group by item and subitem. Sum quantity and count the number of subitems per item.
        select
          t.Item,
          t.Sub_Item,
          sum(t.qty) as GroupQty,
          count(distinct t.sub_item) over (partition by t.Item) as SubItemCount
        from
          YourTable t 
        group by 
          t.item,
          t.sub_item ) x
    where
      x.SubItemCount > 1) y
where
  y.GroupRank = 1 -- Return only the subitems with the lowest sum.