如何在Where子句中使用组函数

时间:2019-06-10 17:27:32

标签: sql oracle group-by

在where子句中是否可以使用组函数?我正在尝试根据以下逻辑插入记录,但仅适用于qty1 的记录

我的代码:

    With t1 as (select item_no, qty,
                min (stock_date)
           From stock_tab
          Where stock_date < SYSDATE
        Group by item_no, qty
     Select item_no, min(t1.qty) qty1, max(t2.qty) qty2, max(stock_date)
         From t1
        Where t1.qty1 < t1.qty2  --incorrect
         --    min(t1.qty) < max(t1.qty2)  --also tried this 
         Group by item_no
        Oder by max(t1.stock_date) desc, max(t1.qty) desc

1 个答案:

答案 0 :(得分:1)

如果要将聚合函数用作过滤器,请搜索having

With t1 as (select item_no, qty,
            min (stock_date)
       From stock_tab
      Where stock_date < SYSDATE
    Group by item_no, qty)
 Select item_no, min(t1.qty) qty1, max(t2.qty) qty2, max(stock_date)
     From t1
     Group by item_no
     having min(t1.qty) < max(t1.qty2)
    Order by max(t1.stock_date) desc, max(t1.qty) desc