将sql查询限制为仅col = 0的行

时间:2017-03-03 16:48:03

标签: sql

我以下列形式查看拍卖数据:

product   auction_id   bid_value   is_winning_bid   reject_reason
iPhone    123          5           1                0
iPhone    123          3           0                1
iPhone    123          2           0                200
iPad      456          1           0                1
iPad      456          10          0                1
iPhone    789          2           0                200
iPhone    999          10          0                1

我想计算其中一个出价有reject_reason = 200并且没有出价的is_winning_bid = 1的拍卖数量,按产品分组。数据集很大,所以我不想输出按auction_id分组。

上表应该导致:

product   total_auctions   count_unfilled_auctions   count_unfilled_auctions_200

iPhone    3                2                         1
iPad      1                1                         0

1 个答案:

答案 0 :(得分:1)

我认为您只需要两个级别的聚合,一个在拍卖级别,一个在产品级别:

select product, count(*) as total_auctions,
       sum(1 - has_winning_bid) as unfulfilled_auctions,
       sum(case when cnt_reject_200 > 0 and has_winning_bid = 1 then 1 else 0 end) as unfulfilled_auctions_200
from (select auction_id, product,
             max(is_winning_bid) as has_winning_bid,
             sum(case when reject_reason = 200 then 1 else 0 end) as cnt_reject_200
      from auctiondata ad
      group by auction_id, product
     ) ad
group by product;