以前总数的SQL百分比

时间:2016-08-11 18:54:39

标签: mysql sql

我们有一个包含三列的ORDERS表:CUSTOMER_ID,ORDER_ID和PRODUCTS_ID。样本数据:

output = [(x,y,w,h) for x,w in zip(range(width)[::tile_size],[tile_size]*(w_tiles-1) + [w_padding]) for y,h in zip(range(height)[::tile_size],[tile_size]*(h_tiles-1) + [h_padding])]

您可以编写查询以获得以下输出吗?

CUSTOMER_ID ORDER_ID    PRODUCT_ID  ORDER_DAY
C1          O1          P1          1-Jan-15
C1          O1          P2          1-Jan-15
C1          O1          P3          1-Jan-15

C2          O2          P6          2-Jan-15
C2          O2          P1          2-Jan-15
C2          O2          P3          2-Jan-15

C1          O3          P1          3-Jan-15
C1          O3          P3          3-Jan-15
C1          O3          P6          3-Jan-15
C1          O3          P7          3-Jan-15

其中:

ORDER_ID    #PRODUCTS   #PRODUCTS_IN_PAST   %PRODUCTS_IN_PAST
O1          3           0                   0%
O2          3           0                   0%
O3          4           2                   50%

1 个答案:

答案 0 :(得分:0)

select order_id, count(*) as numproducts, sum(is_previous), avg(is_previous)
from (select o.*,
             (case when o.product_id in (select o2.product_id
                                         from orders o2
                                         where o2.customer_id = o.customer_id and
                                               o2.order_date < o.order_date
                                         )
                    then 1 else 0
              end) as is_previous
      from orders o
     ) o
group by o.order_id;