通过考虑另一列来计算一列

时间:2020-08-25 13:59:26

标签: sql oracle

这是我的审核表:

id      productnr    invoicenr         price              
1         2            1000             20
2         2            1000             20
3         31           1000             25
4         23           1001             15
5         23           1002             15
6         71           1002             27
7         2            1003             20 

我需要编写2个不同的查询,但我不知道该如何编写它们:

  1. 只有产品2(+总价)有多少张发票?

  2. 多少张发票上有不同的产品,但产品2也有(+总价)?

我想要的结果如下:

Count    totalPrice
1250       206030

1 个答案:

答案 0 :(得分:2)

如果我理解正确,则可以使用两种聚合级别:

select sum(case when num_products = 1 then 1 else 0 end) as has_2_only,
       sum(case when num_products = 1 then total else 0 end) as has_2_total,
       count(*) as has_2,
       sum(total) as has_2_total
from (select invoicenr, sum(price) as total,
             count(distinct product_nr) as num_products,
             max(case when product = 2 then 1 else 0 end) as has_product_2
      from t
      group by invoicenr
     ) i
where has_product_2 = 1