MySQL从周一到周日的过去12周获得订单

时间:2018-06-01 13:56:40

标签: mysql

我有一个表格,用于存储用户发出的每个订单,记录订单的日期,金额和用户ID。我正在尝试创建一个查询,返回特定用户在过去12周内从周一到周日的每周交易。我使用以下查询:

SELECT COUNT(*) AS Orders, 
SUM(amount) AS Total, 
DATE_FORMAT(transaction_date,'%m/%Y') AS Week
FROM shop_orders
WHERE user_id = 123 
AND transaction_date >= now()-interval 3 month
GROUP BY YEAR(transaction_date), WEEKOFYEAR(transaction_date)  
ORDER BY DATE_FORMAT(transaction_date,'%m/%Y') ASC

这会产生以下结果:

Screenshot

然而,这并没有返回用户订购0个订单的周数,也没有返回从周一到周日的订单总和,也没有返回从1到12订购的周数。有没有办法实现这些?

2 个答案:

答案 0 :(得分:1)

实现此目的的一种方法是使用自外连接(在这种情况下,我使用右外连接,但当然左外连接也可以。)

要在星期一开始您的工作周,请按照ngOnInit中最基本的答案[/ 3}}中的建议,使用WEEKDAY从您的专栏transaction_date中减去DATE_SUB的结果。

SELECT 
    COALESCE(t1.Orders, 0) AS `Orders`,
    COALESCE(t1.Total, 0) AS `Total`,
    t2.Week AS `Week`
FROM
(
    SELECT 
        COUNT(*) AS `Orders`, 
        SUM(amount) AS `Total`, 
        DATE(DATE_SUB(transaction_date, INTERVAL(WEEKDAY(transaction_date)) DAY)) AS `Week`
    FROM 
        shop_orders
    WHERE 1=1
        AND user_id = 123 
        AND transaction_date >= NOW() - INTERVAL 12 WEEK
    GROUP BY 
        3
) t1 RIGHT JOIN (
    SELECT 
        DATE(DATE_SUB(transaction_date, INTERVAL(WEEKDAY(transaction_date)) DAY)) AS `Week`
    FROM 
        shop_orders 
    WHERE 
        transaction_date >= NOW() - INTERVAL 12 WEEK 
    GROUP BY
        1
    ORDER BY
        1
) t2 USING (Week)

答案 1 :(得分:0)

要返回没有订单的周数,您必须创建一个包含所有周数的表格。

按照

中组相同字段的订单顺序