多计算查询

时间:2011-06-26 12:09:26

标签: mysql sql

产品表

id      name       description       price

 1      AAA         AAAAAA           10.00
 2      BBB         BBBBBB           12.00
 3      CCC         CCCCCC           15.00
 4      DDD         DDDDDD            8.00
 5      EEE         EEEEEE           12.50

销售表

trackid     productid     affiliateid     paymentstatus     refundid

   1           2               1           COMPLETED         1
   2           2               0           DONE              null
   3           3               1           COMPLETED         null
   4           3               0           COMPLETED         null
   5           3               0           COMPLETED         null
   6           5               5           DONE              null
   7           5               0           COMPLETED         2
   8           5               2           COMPLETED         null
   9           2               0           DONE              null
  10           3               1           COMPLETED         3

对于销售表

  • 如果特定销售没有会员,那么affiliateid将为0,否则为affiliateid(我有另一个用户列表供应商及附属公司的表)

  • 如果特定销售已退款(因任何原因),则refundid将设置为某个值,否则为null

  • paymentstatus可以包含2个值中的任意一个,已完成并已完成

现在我需要查询列出产品表中每种产品的以下数据

 productid       name       totalsales      affsales        refunds

     1           AAA           0               0               0
     2           BBB           1               1               1
     3           CCC           4               2               1
     4           DDD           0               0               0 
     5           EEE           2               1               1

totalsales:salesstatus的销售额为“已完成”

affsales:salesstatus的销售额为“COMPLETED”且affiliateid不等于0

退款:salesstatus的销售额为“已完成”且退款为空

如何构建此特定查询?

1 个答案:

答案 0 :(得分:2)

select 
      p.name,
      SalesSummary.productid,
      COALESCE( SalesSummary.TotalSales, 0 ) TotalSales 
      COALESCE( SalesSummary.AffSales, 0 ) AffSales 
      COALESCE( SalesSummary.Refunds, 0 ) Refunds 
   from
      product p
         left join
            ( select s.productid,
                    count(*) TotalSales 
                    sum( if( s.affiliateID > 0, 1, 0 )) affSales,
                    sum( if( ifnull( s.RefundID, 0 ) > 0, 1, 0 )) Refunds
                 from 
                    sales s
                 where
                    s.PaymentStatus = 'COMPLETED'
                 group by
                    s.productid
            ) SalesSummary
         on p.id = SalesSummary.productid