I have a table with rows per user per day.
I want to group by month and year to produce a summary for a given month.
The problem is, is that it is selecting the value of the first row (ie the 1st of September instead of 5th September) which gives me the wrong number because I want the latest running total of the column.
I have tried:
SELECT SUM(prospectCount) FROM report_sales_day AS RSD
WHERE userId = 93
AND YEAR(date) = YEAR('2014-09-01')
AND MONTH(date) = MONTH('2014-09-01')
AND (SELECT MAX(RSDI.date)
FROM report_sales_day AS RSDI
WHERE MONTH(RSDI.date) = MONTH(RSD.date)
AND YEAR(RSDI.date) = YEAR(RSD.date)) = MAX(date)
GROUP BY YEAR(date), MONTH(date)
But this just gives me an error and I can't think of any other way to do it.
Does any one know what I need to do to achieve the result I am after?
I have many columns in my table, some need to be SUM(), AVG() and others I just need the last value of a given month.
Try this:
SELECT SUM(prospectCount)
FROM report_sales_day AS RSD
INNER JOIN (SELECT userId, MAX(RSDI.date) AS `date`
FROM report_sales_day AS RSDI
WHERE MONTH(RSDI.date) = MONTH('2014-09-01') AND YEAR(RSDI.date) = YEAR('2014-09-01')
) AS A ON RSD.userId = A.userId AND RSD.date = A.date
WHERE userId = 93 AND YEAR(RSD.date) = YEAR('2014-09-01') AND
MONTH(RSD.date) = MONTH('2014-09-01')
GROUP BY YEAR(RSD.date), MONTH(RSD.date)
I think your query should be like this. You have to use backticks around `date`
SELECT SUM(prospectCount) FROM report_sales_day AS RSD
WHERE userId = 93
AND YEAR(`date`) = YEAR('2014-09-01')
AND MONTH(`date`) = MONTH('2014-09-01')
AND MAX(`date`) = (SELECT MAX(RSDI.date)
FROM report_sales_day
WHERE MONTH(RSDI.date) = MONTH(RSD.date)
AND YEAR(RSDI.date) = YEAR(RSD.date))
GROUP BY YEAR(`date`), MONTH(`date`)
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.