Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL: Calculate sum total of all the figures in a column where has specific date

Tags:

php

mysql

sum

How can I get the sum of the column price for a specific month.

The date column is a varchar(10) and the date format is European ( dd-mm-yy ).

Here is a sample of my table:

enter image description here

Currently to select all sum of price I use:

case 'get':

            $q=mysql_real_escape_string($_GET['q']);
            $query="SELECT sum(price) FROM Fuel";

            $result = mysql_query($query);


            $json = array();
            while($row = mysql_fetch_array($result))
            {
                $json['price']=$row['price'];
            }
            print json_encode($json);




            mysql_close();


            break;

So how can I get the sum of column price for month 09-2012.

like image 316
jQuerybeast Avatar asked Nov 18 '12 08:11

jQuerybeast


People also ask

Can we use sum with where clause?

SQL SUM() with where clause We can selectively find the sum of only those rows, which satisfy the given condition. To do this, we can use the where clause in the SQL statement.

How do I get the sum of all values in a column in SQL?

If you need to add a group of numbers in your table you can use the SUM function in SQL. This is the basic syntax: SELECT SUM(column_name) FROM table_name; The SELECT statement in SQL tells the computer to get data from the table.

Can I do a sum of a count in MySQL?

COUNT() is used to count the number of rows for a given condition. COUNT() works on numeric as well as non-numeric values. SUM() is used to calculate the total sum of all values in the specified numeric column.


2 Answers

First change the data type of your date column (remember to update your application code appropriately):

ALTER TABLE Fuel ADD newdate DATE;
UPDATE Fuel SET newdate = STR_TO_DATE(date, '%d-%m-%Y');
ALTER TABLE Fuel DROP date, CHANGE newdate date DATE FIRST;

Then you can:

SELECT SUM(price) FROM Fuel WHERE date BETWEEN '2012-09-01' AND '2012-09-30'
like image 53
eggyal Avatar answered Nov 15 '22 18:11

eggyal


This will work for you:

SELECT 
  sum(price) 
FROM Fuel
WHERE datefield = 'somedate';

But you have to watch out the format entered in the date parameter, because it will be compared as a string literal not as a date object. However, you should store these dates in a column of data type DATE instead.

Update:

How can I select sum for all months with 09?

To select only records for a specific month, you can use the MySQL function MONTH like so:

SELECT 
  SUM(price) 
FROM Fuel
WHERE MONTH(`date`) = 9;

SQL Fiddle Demo

like image 39
Mahmoud Gamal Avatar answered Nov 15 '22 18:11

Mahmoud Gamal