我有一个每个用户每天都有行的表。
我希望按月和年分组,以生成给定月份的摘要。
问题是,它是选择第一行的值(即9月1日而不是9月5日),这给了我错误的数字,因为我想要列的最新运行总数。
我试过了:
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)
但这只是给了我一个错误,我想不出任何其他方法去做。
有没有人知道我需要做些什么来达到我追求的结果?
我的表中有很多列,有些需要是SUM(),AVG()和其他我只需要给定月份的最后一个值。
答案 0 :(得分:1)
试试这个:
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)
答案 1 :(得分:0)
我认为您的查询应该是这样的。你必须在`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`)