Oracle SQL: select where 条件左侧w/o using transaction

Oracle SQL: select on the left side of the where condition w/o using transaction

我是 SQL (Oracle) 的新手,我了解基础知识。但是有一件事我想知道,但没有找到任何合适的答案。假设我有这个 table_1:

 shipno   itemno   amount   weight_in_kg
 -  -  -  -  -  -  -  -  -  -  -  -  -  -
 001         1        1          50 
 001         6        6          60
 002         2        1          30
 002         6        3          30
 003         1        2         100
 004         5       10          25

是否可以像这样创建查询以显示包裹总重量超过 100 公斤的所有船号:

SELECT * 
FROM table_1 
WHERE (
       SELECT sum(weight) 
       FROM table_1 
       WHERE shipno in (001, 002, 003, 004)
 ) >= 100

得到这个输出:

 shipno   itemno   amount   weight_in_kg
 -  -  -  -  -  -  -  -  -  -  -  -  -  -
 001       1         1        50 
 001       6         6        60
 003       1         2       100

有没有排除事务或者脚本的方案? 我知道我绝对可以通过交易解决这个问题,但我只是好奇如果没有交易是否可以解决。

提前感谢您的回答

select *
from   your_table
where  shipno in (select shipno
                  from   your_table
                  group by shipno
                  having sum(weight) > 100)

如果您只是 shipno 它是一个简单的聚合。 HAVING 子句像 WHERE 子句一样充当过滤器,但使用聚合值作为其标准。

select shipno 
       , sum(weight_in_kg) as total_weight_in_kg
from table1
group by shipno 
having sum(weight_in_kg) > 100

如果您想要 table 中的所有详细信息,您可以使用此查询的变体作为子查询:

select *
from table1
where shipno in (select shipno 
                 from table1
                 group by shipno 
                 having sum(weight_in_kg) > 100
    )

另一种选择是使用 window 函数:

select shipno, itemno, amount, weight_in_kg
from (
  select shipno, itemno, amount, weight_in_kg, 
         sum(weight_in_kg) over (partition by shipno) as total_weight
  from the_table
) t
where total_weight > 100;

如果您只需要 shipno,那么 GROUP BY 查询是更好更快的解决方案。但是,如果您需要这些货件的所有行和列,这可能比 sub-select 和额外的分组依据更快。