我正在尝试从给定的 table 中获取所有 "num",其中 "OUT" > "IN"

I am trying to fetch all those "num" from the given table where the "OUT" > "IN"

对于一个“num”值,我们可以有多个记录。我们需要按 num.

的升序打印输出

Table :

create table bill
( 
  type varchar(5),
  num varchar(12),
  dur int
);


  insert into bill values
  ('OUT',1818,13),
  ('IN', 1818,10),
  ('OUT',1818,7),
  ('OUT',1817,15),
  ('IN',1817,18),
  ('IN',1819,18),
  ('OUT',1819,40),
  ('IN',1819,18)

这就是我要查询的内容:我在不同的子查询中对“类型”的记录进行分组,并获取“OUT”>“IN”的记录。

select a.num
from 
(select num,sum(dur) as D
 from bill  
 where type ='OUT'
 group by num) a ,

(select num,sum(dur) as D
        from bill  
         where type ='IN'
            group by num) b 
        
where a.D > b.D
group by a.num
order by 1

My output:     Expected output:
num             num
1817           1818
1818           1819
1819

谢谢

使用条件聚合:

SELECT num
FROM bill
GROUP BY num
HAVING SUM(CASE WHEN type = 'OUT' THEN dur ELSE 0 END) >
       SUM(CASE WHEN type = 'IN' THEN dur ELSE 0 END);

我会在子查询中使用条件聚合函数并添加 where type in ('IN','OUT') 如果您在第一列 type 上创建索引

可能会获得更好的性能
SELECT num
FROM (
    SELECT num,
           SUM(CASE WHEN type = 'OUT' THEN dur ELSE 0 END) outval, 
           SUM(CASE WHEN type = 'IN' THEN dur ELSE 0 END) inval
    FROM bill  
    WHERE type in ('IN','OUT')
    GROUP BY num
) t1
WHERE outval > inval

sqlfiddle