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 {


    }
?>
DarkBee
  • 16,592
  • 6
  • 46
  • 58
user2767046
  • 13
  • 1
  • 6
  • The big letters are for headers. Could you please edit your question and make it readable. – cpap Apr 19 '17 at 07:39
  • You should take a look at `YEAR()` and `SUM()`: https://dev.mysql.com/doc/refman/5.7/en/group-by-functions.html – jeroen Apr 19 '17 at 07:39

3 Answers3

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.

Qirel
  • 25,449
  • 7
  • 45
  • 62
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 {


    }

    ?>
Simos Fasouliotis
  • 1,383
  • 2
  • 16
  • 35
-1

Group by With year and Month will achieve this

GROUP BY YEAR(Date), MONTH(Date)