简体   繁体   中英

PHP and SQL - How to select highest sum of all months in a current year?

So I have table 'item' in database with attributes: id, dateItem, price.

I want to find MAX(SUM(price)) for some month in a current year.

id  dateItem (Format: yyyy-mm-dd)    price
1   25.06.2015.                      986,69
2   21.06.2015.                      1564
3   22.03.2015.                      23,56
4   21.03.2015.                      187,23
5   01.03.2015.                      489,33
6   06.10.2015.                      975,26

I came up with something like this, but I know it's not ok. Please, help :s

$sql = "SELECT MAX(SUM(price)) FROM item WHERE DATE('Y') = 2015 AND 
dateItem between DATE('Y/m/1') and DATE('Y/m/31')";

You can't nest aggregation functions. You need to use a subquery.

SELECT MAX(pricesum) 
FROM (SELECT SUM(price) AS pricesum
      FROM item
      WHERE YEAR(dateItem) = YEAR(NOW())
      GROUP BY MONTH(dateItem)) AS subquery

You can do this with ORDER BY and LIMIT :

SELECT SUM(price) AS pricesum
FROM item
WHERE YEAR(dateItem) = YEAR(NOW())
GROUP BY MONTH(dateItem)
ORDER BY pricesum DESC
LIMIT 1;

If you want to know the month as well, you can include that in the SELECT clause.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM