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:
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.
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.
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.
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.
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'
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With