查询以获取订单小于先前订单的客户列表

时间:2016-10-12 23:31:54

标签: mysql sql database stored-procedures data-warehouse

我正在尝试编写一个sql来获取总订购单位始终小于之前订单的客户列表。如在第n顺序中的总数量小于在第n-1阶等的总数量

用于创建和填充表格的SQL

create table orders (order_id int, customer_id varchar(5), order_date date, product_id varchar(5), quantity int);

Insert into orders values(01,'C1','2000-01-01','P1',10);
Insert into orders values(02,'C2','2002-01-01','P2',15);
Insert into orders values(03,'C3','2002-04-01','P3',17);
Insert into orders values(04,'C4','2003-04-01','P1',20);
Insert into orders values(05,'C4','2006-01-01','P2',1);
Insert into orders values(06,'C1','2006-05-01','P5',7);

我假设我需要根据Order_id序列号编写一个过程和LOOP。进入循环后,我需要选择对应于order_id的product_id和数量Q.然后检查是否对于相同的order_id,是否有任何其他数量Q1小于Q.如果是,则打印customer_id。 如果没有,则order_id移动到下一个order_id。

我不确定如何实施我检查数量列的部分,以检查是否有任何其他数量Q1< Q for order_id?

请澄清

4 个答案:

答案 0 :(得分:1)

您应该根据order_date计算每个customer_id的row_numbers。然后,您必须为每个客户加入第n行到第n-1行,并检查他们是否至少有一个订单,其数量小于之前的订单。

SQL Fiddle

select t1.customer_id
from (select o.*,
      @rn:=if(@previous=customer_id,@rn,0) + 1 as rownum,
      @previous:=customer_id
      from orders o, (select @rn:=0,@previous:=NULL) t
      order by customer_id,order_date) t1
join (select o.*,
      @rn:=if(@previous=customer_id,@rn,0) + 1 as rownum,
      @previous:=customer_id
      from orders o
      order by customer_id,order_date) t2 
on t1.customer_id=t2.customer_id and t1.rownum=t2.rownum-1
group by t1.customer_id
having count(case when t2.quantity < t1.quantity then 1 end) >= 1

答案 1 :(得分:1)

一种方法使用相关子查询:

select o.*
from (select o.*,
             (select o2.quantity
              from orders o2
              where o2.customer_id = o.customer_id and
                    o2.product_id = o.product_id and
                    o2.order_id < o.order_id
              order by o2.order_id desc
              limit 1
             ) prev_quantity
      from orders o
     ) o
where o.prev_quantity > o.quantity;

答案 2 :(得分:0)

我相信一个简单的连接就可以为你做这件事,以及一个嵌入式查询,根据日期确定要加入的正确行。

SELECT o1.customer_id, o2.order_date, o1.quantity - o2.quantity AS quantity_less
FROM orders o1
INNER JOIN orders o2 ON o2.customer_id = o1.customer_id AND
                        o2.order_date = (SELECT MIN(order_date) FROM orders
                                         WHERE order_date > o1.order_date AND customer_id = o1.customer_id)
WHERE o2.quantity < o1.quantity

答案 3 :(得分:-1)

SELECT Customer_ID
FROM
(
SELECT c.customer_id,c.order_date,c.quantity,p.quantity AS PreviousQuantity FROM orders c left join orders p ON c.customer_id = p.customer_id AND c.order_date> p.order_date
WHERE c.quantity< p.quantity AND c.order_date>p.order_date
)A
EXCEPT
SELECT Customer_ID
FROM
(
SELECT c.customer_id,c.order_date,c.quantity,p.quantity AS PreviousQuantity FROM orders c left join orders p ON c.customer_id = p.customer_id AND c.order_date> p.order_date
WHERE c.quantity> p.quantity  AND c.order_date>p.order_date
)B