从 mysql 获取数据并以周为单位对它们进行分组并显示日期

Get data from mysql and group them in weeks and also display the dates

我每周打印一次数据。我需要在查询中添加一件事。我想要一周的开始和结束日期以及数据。

目前数据是这样的

        [0] => Array
            (
                [WEEK] => 7

                [total_sub_total] => 110.30
                [total_tax] => 9.92
                [total_restaurant_delivery_fee] => 0
            )


        [0] => Array
            (
                [WEEK] => 8

                [total_sub_total] => 6540.00
                [total_tax] => 1046.40
                [total_restaurant_delivery_fee] => 0
            )

我想要那个星期的日期。例如,它应该是

[0] => Array
                (
                    [WEEK] => 8,
                    [starting_week_date] => 2018-02-21 13:18:10,
                    [ending_week_date] => 2018-02-26 13:18:10,


                    [total_sub_total] => 6540.00
                    [total_tax] => 1046.40
                    [total_restaurant_delivery_fee] => 0
                )

这是代码

public function getWeeklyEarnings($restaurant_id)
    {


        return $this->find('all', array(


            //'contain' => array('OrderMenuItem', 'Restaurant', 'OrderMenuItem.OrderMenuExtraItem', 'PaymentMethod', 'Address','UserInfo','RiderOrder.Rider'),

            'conditions' => array(



                'Order.restaurant_id' => $restaurant_id,
                'Order.status' => 2,
                'Order.created >    DATE_SUB(NOW(), INTERVAL 4 WEEK)'



            ),
            'fields' => array(


                'WEEK(Order.created) AS WEEK',

                'sum(Order.sub_total)   AS total_sub_total',
                'sum(Order.tax)   AS total_tax',
                'sum(Order.restaurant_delivery_fee)   AS total_restaurant_delivery_fee',

            ),
            'group' => array('WEEK(Order.created)'),

            'recursive' => 0

        ));
    }

没有简单的函数可以在给定周数的情况下生成周间隔(或 start/end 一周中的日期)。您必须手动查找这些日期。
试试这个:

'fields' => array(
    'WEEK(Order.created) AS WEEK',

    'DATE_ADD(Order.created, INTERVAL(1-DAYOFWEEK(Order.created)) DAY) AS week_start',
    'DATE_ADD(Order.created, INTERVAL(7-DAYOFWEEK(Order.created)) DAY) AS week_end',

    'sum(Order.sub_total)   AS total_sub_total',
    'sum(Order.tax)   AS total_tax',
    'sum(Order.restaurant_delivery_fee)   AS total_restaurant_delivery_fee'
)

DAYOFWEEK() 函数 returns 一个从 1(星期日)到 7(星期六)的整数。因此,如果 Order.created 恰好是星期二,我们会得到以下语句:

DATE_ADD(Order.created, INTERVAL -2 DAY)

这基本上意味着“从 Order.created(那一周的星期日)中减去 2 天,并且:

DATE_ADD(Order.created, INTERVAL 4 DAY)

得出该周星期五的日期。

或者,您可以尝试:

'fields' => array(
    'WEEK(Order.created) AS WEEK',

    'MIN(Order.created) as week_start',
    'MAX(Order.created) as week_end',

    'sum(Order.sub_total)   AS total_sub_total',
    'sum(Order.tax)   AS total_tax',
    'sum(Order.restaurant_delivery_fee)   AS total_restaurant_delivery_fee'
)

但是您必须确保一周中的每一天都有订单。

希望对您有所帮助。