简体   繁体   中英

How to return each week data as array in mysql query grouped by week?

Here is my data, you can have a test at sqlfiddle :

CREATE TABLE yourtable
    (`day` datetime, `val` int)
;

INSERT INTO yourtable
    (`day`, `val`)
VALUES
    ('2012/01/01', 465),
    ('2012/01/02', 896),
    ('2012/08/15', 678),
    ('2012/09/01', 324),
    ('2012/12/02', 74),
    ('2012/12/03', 65),
    ('2012/12/04', 35)
;

I try to query all the data and hope they return in an array rows , which is grouped by week, my code to do this is:

select *, week(day) Week,
  year(day) Year
  from yourtable
group by week(day), year(day)

unfortunately, it is not work as expected, I would like it output like:

rows[0]= first two records (as a array, such that I can get them by `rows[0][0]` and so on);
rows[1]=the next one record (as a array);
rows[2]=the next one record (as a array);
rows[3]=the next three records(as a array);

The point is that they are in the same WEEK.

Any help?

Here what you can do,

select 
week(day) as Week,
year(day) Year,
group_concat(val) as val
from yourtable
group by week(day)

This will merge common val with comma separation grouping by the week.

You can retrieve these data and use as per need.

If you need all as a row then u just select all record without any group by and then they all will appear as a row.

http://sqlfiddle.com/#!2/82a51/14

As MySQL does not have any array-type (or at least no GROUP BY-aggregator to create one) like Oracle I would use

SELECT *, WEEK(day) Week,
  YEAR(day) Year
  FROM yourtable
ORDER BY year(day), week(day)

and build the arrays when retrieving the result, creating a new row every time the values of Week and Year in the current row are different from the previous. Query on sqlfiddle

To give you an idea how to do the grouping, this is sample PHP code to group the rows:

$plain_result = Array(
    Array('day' => '2012-01-01 00:00:00', 'val' => 465, 'Week' => 1, 'Year' => 2012),
    Array('day' => '2012-01-02 00:00:00', 'val' => 896, 'Week' => 1, 'Year' => 2012),
    Array('day' => '2012-08-05 00:00:00', 'val' => 678, 'Week' => 33, 'Year' => 2012)
);

$grouped_result = Array();
$previousWeek = null;
$previousYear = null;
foreach ($plain_result as $row) {
    if($previousWeek != $row['Week'] || $previousYear != $row['Year'] || count($grouped_result) == 0) {
        $previousWeek = $row['Week'];
        $previousYear = $row['Year'];
        $grouped_result[] = Array();
    }
    $grouped_result[count($grouped_result) - 1][] = $row;
}

var_dump($grouped_result);

$plain_result should be easy to build or alternatively instead of first retrieving as an array of rows directly do this while retrieving individual rows.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM