0

How can I create a result, in either PHP or MySQL which will show the year 2005, as example, and sum all results

Example input

-------------------------
Date       \    Quantiti
-------------------------
12-05-2005 \      5
-------------------------
23-08-2005 \      8
-------------------------
11-02-2006 \      4
-------------------------
26-09-2006 \      2
-------------------------

Example ouput

---------------------------
year    \    Total
---------------------------
2005    \     13
---------------------------
2006    \     6
---------------------------

<?php
$sql = "SELECT * FROM mytable ORDER BY date DESC"; 
$result = $conn->query($sql);

if ($result->num_rows > 0) {

    while($row = $result->fetch_assoc()) {
        $date = $row["date"];
        $quantiti = $row["quantiti"];

        // here i need code for each new year 
    }
    } else {


    }
?>
2
  • The big letters are for headers. Could you please edit your question and make it readable. Commented Apr 19, 2017 at 7:39
  • You should take a look at YEAR() and SUM(): dev.mysql.com/doc/refman/5.7/en/group-by-functions.html Commented Apr 19, 2017 at 7:39

3 Answers 3

1

You can SUM() all the quantyties which have the same year by grouping the years, using GROUP BY YEAR(date). A simple query like this should do the job

SELECT SUM(Quantiti) as `total`, 
       YEAR(date) as `year` 
FROM mytable 
GROUP BY YEAR(date)

Note that the returning result is named total and year, as per your example output.

Sign up to request clarification or add additional context in comments.

Comments

0

You can use SUM to sumup the quantity and GROUP BY to group results by year.

A sql query for your needs would be:

SELECT YEAR(Date), SUM(Quantiti) 
FROM mytaple
GROUP BY YEAR(Date)

So your code would be:

<?php
$sql = "SELECT YEAR(Date) as y, SUM(Quantiti) as q FROM mytaple GROUP BY YEAR(Date)"; 
$result = $conn->query($sql);

if ($result->num_rows > 0) {

    while($row = $result->fetch_assoc()) {
        $date[] = $row["y"];
        $quantiti[] = $row["q"];
    }
for($i<0; $i<count($date);$i++) {
        echo $date[$i]."/".$quantiti[$i];
    }
    } else {


    }

    ?>

2 Comments

Thanks the idea was 'GROUP BY'. But the issue is i don't know how to adapt it in my code in PHP :(
Thank you its working now, appreciate it
-1

Group by With year and Month will achieve this

GROUP BY YEAR(Date), MONTH(Date)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.