How to group the records by year?

Asked

Viewed 40 times

-1

How would I group the years that are equal? in my table there is a record with the year 2019, one with 2020, and 3 with 2021, but in time to show the result the records that are with the year 2021 but with different months do not group. It’s like:

2019
mes 3

2020
mes 4

2021
mes 1
2021
mes 2
2021
mes 3

instead of:

2021
mes 1
mes 2
mes 3

Look how I’m doing:

$sel = $conn->prepare("SELECT DISTINCT Year(dateFull) as year,  Month(dateFull) as month,  Day(dateFull) as day from usersInfo ORDER BY year, month, day");
    $sel->execute();
    $data = $sel->fetchAll();
    foreach ($data as $key => $value) {
        echo $value['year'] . "<br>";
        echo $value['month'] . "<br>";
        echo $value['day'] . "<br>";
    }

1 answer

0

Create a variable to store the current year $current_year = ""; and print only if (if) verify that the registration in question is different from the year previously printed. Follow suggested code:

$sel = $conn->prepare("SELECT DISTINCT Year(dateFull) as year,  Month(dateFull) as month,  Day(dateFull) as day from usersInfo ORDER BY year, month, day");
    $sel->execute();
    $data = $sel->fetchAll();
    $current_year = "";
    foreach ($data as $key => $value) {
        if ($current_year <> $value['year']){
            echo $value['year'] . "<br>";
            $current_year = $value['year'];
        }
        echo $value['month'] . "<br>";
        echo $value['day'] . "<br>";
    }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.