加入Max和pre-Max行

时间:2016-03-15 07:46:11

标签: mysql sql join group-by max

我有两个表'sites'和'index_log'。表'sites'是关于站点的信息(userid,name,description ...)表index_log具有列date,index_count和siteid。所以我想获得每个站点的last和previous index_log行,其中userid = 10.这是我的变体:

 SELECT ff.id,
        ff.siteurl,
        ff.last_count,
        ff.last_date,
        il2.index_count as previous_count,
        MAX(il2.date) as previous_date
FROM (
    SELECT s.siteurl,
            s.id,
            il.index_count as last_count,
            MAX(il.date) as last_date
    FROM sites s 
    LEFT JOIN index_logs il ON il.siteid = s.id
    WHERE s.userid = 10
    GROUP BY s.id
    ) as ff
LEFT JOIN index_logs il2 ON il2.siteid = ff.id AND il2.date < ff.last_date
GROUP BY ff.id

但是在此变体中,index_count列(last和previous)与max date row不匹配。我希望得到你的帮助。

1 个答案:

答案 0 :(得分:0)

这将为每个sites.id提供最后2个日志条目。

; with CTE as
(
    SELECT s.siteurl, s.id, il.index_count, il.date, 
           RN = ROW_NUMBER() OVER (PARTITION BY s.id ORDER BY il.date DESC)
    FROM   sites s
    JOIN   index_logs il ON il.siteid = s.id
    WHERE  s.userid = 10
)
SELECT *
FROM   CTE
WHERE  RN <= 2