如果值在特定时间段之前和之后存在,则创建日期列表

时间:2019-02-26 08:40:43

标签: mysql sql

我有下表,您也可以在SQL Fiddle here中找到该表:

CREATE TABLE Orders (
    Customer TEXT,
    Order_Date DATE
);

INSERT INTO Orders
(Customer, Order_Date)
VALUES 
("Customer A", "2017-05-23"),
("Customer A", "2019-01-03"),
("Customer A", "2019-02-15"),
("Customer A", "2019-02-16"),

("Customer B", "2018-09-10"),
("Customer B", "2019-01-09"),

("Customer C", "2016-09-04"),
("Customer C", "2019-02-12"),
("Customer C", "2019-02-20"),

("Customer D", "2017-03-15"),
("Customer D", "2019-02-17"),
("Customer D", "2019-02-19"),
("Customer D", "2019-02-20"),

("Customer E", "2019-02-03"),
("Customer E", "2015-10-12");

您可以看到该表显示了来自不同客户的订单日期。
我使用以下SQL为以下客户获得unique count of orders

a) placed an order in February 2019 and
b) did not place an order in the 12 month before and
c) placed an order before this 12 months period

请参考答案here

SELECT o.Customer,
       MAX( o.Order_Date >= '2019-02-01' AND o.Order_Date < '2019-03-01' ) as num_feb_orders
FROM ORDERS o
GROUP BY o.Customer
HAVING SUM( o.Order_Date >= '2019-02-01' AND o.Order_Date < '2019-03-01' ) > 0 AND
       SUM( o.Order_Date >= '2018-02-01' AND o.Order_Date < '2019-02-01' ) = 0 AND
       SUM( o.Order_Date < '2018-02-01' ) > 0 ;

到目前为止,所有这些都工作正常。


但是,现在我不是要根据客户来制作GROUP BY,而是要根据GROUP BY来制作Order_Date,所以所有latest order_dates in February都是指完全满足客户需求的客户以上标准应列出。结果应如下所示。

Order_Date      UniqueOrders
2019-02-03            1       --> Customer E
2019-02-20            2       --> Customer C and Customer D

要使此功能生效,我需要更改什么代码?

2 个答案:

答案 0 :(得分:2)

希望这有助于我将给定查询用作子查询来获得所需的输出,

SELECT OrderDate, 
    (COUNT(*) 
     FROM (
         SELECT o.Customer, MAX(o.Order_Date) AS OrderDate,
             MAX( o.Order_Date >= '2019-02-01' AND o.Order_Date < '2019-03-01' ) AS UniqueOrders
         FROM ORDERS AS o
         GROUP BY o.Customer
        HAVING SUM( o.Order_Date >= '2019-02-01' AND o.Order_Date < '2019-03-01' ) > 0 AND
           SUM( o.Order_Date >= '2018-02-01' AND o.Order_Date < '2019-02-01' ) = 0 AND
           SUM( o.Order_Date < '2018-02-01' ) > 0)a
GROUP BY OrderDate ;

答案 1 :(得分:0)

您可以只使用子查询:

SELECT last_feb_order_date, COUNT(*) as num_customers
FROM (SELECT o.Customer,
             MAX( o.Order_Date >= '2019-02-01' AND o.Order_Date < '2019-03-01' ) as num_feb_orders,
             MAX(CASE WHEN o.Order_Date >= '2019-02-01' AND o.Order_Date < '2019-03-01' THEN o.Order_Date END) as last_feb_order_date
      FROM ORDERS o
      GROUP BY o.Customer
      HAVING SUM( o.Order_Date >= '2019-02-01' AND o.Order_Date < '2019-03-01' ) > 0 AND
             SUM( o.Order_Date >= '2018-02-01' AND o.Order_Date < '2019-02-01' ) = 0 AND
             SUM( o.Order_Date < '2018-02-01' ) > 0
     ) oc
GROUP BY last_feb_order_date
ORDER BY last_feb_order_date;