Oracle SQL:使用事务在where条件的左侧选择w / o

问题描述 投票:0回答:3

我是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

有没有排除交易或脚本的解决方案?我知道我绝对可以通过交易来解决这个问题,但我很好奇是否可以在没有交易的情况下完成。

提前感谢您的回答

sql oracle where-clause
3个回答
1
投票

如果你只是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

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

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

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

0
投票

另一个选择是使用窗口函数:

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查询是更好更快的解决方案。但是,如果您需要这些货件的所有行和列,这可能比具有附加组的子选择更快。

© www.soinside.com 2019 - 2024. All rights reserved.