按一个月中的星期分组数据并获取开始和结束日期

问题描述 投票:0回答:1

我想在一个月的一周内对数据进行分组?这是示例数据

date            point1  point2
"2020-03-01"    1000    2000
"2020-03-02"    1000    2000
"2020-03-03"    1000    2000
"2020-03-04"    1000    2000
"2020-03-05"    1000    2000
"2020-03-06"    1000    2000
"2020-03-07"    1000    2000
"2020-03-08"    1000    2000
"2020-03-09"    1000    2000
"2020-03-10"    1000    2000
"2020-03-11"    1000    2000
"2020-03-12"    1000    2000
"2020-03-13"    1000    2000
"2020-03-14"    1000    2000
"2020-03-15"    1000    2000
"2020-03-16"    1000    2000
"2020-03-17"    1000    2000
"2020-03-18"    1000    2000
"2020-03-19"    1000    2000
"2020-03-20"    1000    2000
"2020-03-21"    1000    2000
"2020-03-22"    1000    2000
"2020-03-23"    1000    2000
"2020-03-24"    1000    2000
"2020-03-25"    1000    2000
"2020-03-26"    1000    2000
"2020-03-26"    1000    2000
"2020-03-27"    100     2000
"2020-03-28"    1000    2000
"2020-03-29"    1000    2000
"2020-03-30"    1000    2000

我想在一个月中按周分组,并获取开始和结束日期,我该怎么做?

我尝试使用laravel,代码如下

$startDate = date('Y-m-d', strtotime($request->get('start_date')));
$endDate = date('Y-m-d', strtotime($request->get('end_date')));

$transactions = $this->transaction
                ->select(
                    DB::raw("date_trunc('WEEK',(date + interval '1 day'))- interval '1 day' AS week"),
                    DB::raw('sum("point1" + "point2") total')
                )
                ->groupBy('week')
                ->whereDate('date', '>=', $startDate)
                ->whereDate('date', '<=', $endDate)
                ->get();

上面的代码将在下个月的下个星期累加,例如日期29-03-2020继续到2020-04-04,我不想这样做,我只想在月份的最后一个日期结束(2020-03-31)

我要说的是

start_date  end_date    total
2020-03-01  2020-03-07  21000
2020-03-08  2020-03-14  21000
2020-03-15  2020-03-21  21000
2020-03-22  2020-03-28  21000
2020-03-29  2020-03-31  21000

非常感谢您的帮助。

laravel postgresql
1个回答
0
投票

总数据保持在where条件下,一周的开始和一周的结尾与where条件不匹配。您应该使用php编辑结果中第一周的start_date值和结果中最后一周的end_date

$transactions[0]->start_date = $startDate ? $startDate : $transactions[0]->start_date;
$transactions[$transactions->count() - 1]->end_date = $endDate ? $endDate : $transactions[$transactions->count() - 1];
© www.soinside.com 2019 - 2024. All rights reserved.