我有一个cron脚本,每天将活动用户的总数写到一个表中。我现在尝试生成一个简单的报告,该报告将显示每个月的“高水位线”。由于某些帐户在该月到期,因此最高数目可能不是在月底。

这是我的桌子结构的一个例子

tblUserLog
-----------
record_id   INT(11)   // PRIMARY KEY
run_date    DATE      // DATE RUN
ttl_count   INT(11)   // TOTAL FOR DAY


样本数据:

record_id      run_date      ttl_count
1              2013-06-01    500
2              2013-06-10    510
3              2013-06-20    520
4              2013-06-30    515
5              2013-07-01    525
6              2013-07-10    530
7              2013-07-20    540
8              2013-07-31    550
9              2013-08-01    560


我想返回的是:

record_id   run_date        ttl_count
3           2013-06-20      520
8           2013-07-31      550
9           2013-08-01      560


我试过两个接近的查询...

// This will give me the total for the first of the month
SELECT s.record_id, s.run_date, s.ttl_count
FROM tblStatsIndividual s
JOIN (
    SELECT record_id
    FROM tblStatsIndividual
    GROUP BY DATE_FORMAT(run_date, '%Y %m')
    HAVING MAX(ttl_count)
) s2
ON s2.record_id = s.record_id
ORDER BY run_date DESC


这将返回每月第一个月的总计,以及record_id和总计的正确日期。

试过这个...

SELECT record_id,max(run_date), max(ttl)
FROM (
    SELECT record_id,run_date, max(ttl_count) AS ttl
    FROM tblStatsIndividual
    GROUP BY DATE_FORMAT(run_date, '%Y %m')
) a
GROUP BY DATE_FORMAT(run_date, '%Y %m')
ORDER BY run_date DESC


这个似乎获得了正确的“高水位标记”,但是它没有返回record_id或高水位标记行的run_date。

如何获得最高记录的record_id和run_date?

最佳答案

就像是

Select detail.Record_ID, detail.Run_Date, detail.ttl_Count
From tblStatsIndividual detail
Inner Join
(Select Year(run_date) as Year, Month(Run_date) as Month, Max(ttl_count) as ttl
From tblStatsIndividual
Group By Year(run_date), Month(Run_date)) maximums
On maximums.Year = Year(detail.Run_date) and maximums.Month = Month(detail.Run_date)
and maximums.ttl = detail.ttl_count


应该做。注意根据您的要求,如果您在同一个月内有两个记录具有相同(并且是当月最高)的ttl_count,则它们都将被返回。

10-01 17:00
查看更多