获取mysql中的最后和大多数值

时间:2016-06-01 18:45:39

标签: mysql sql

我有一个像user_places这样的表:

user_id  recorded_date  place_visited
2        2016-04-05     NY
2        2016-04-07     UK
2        2016-04-08     UK
2        2016-04-08     UK
3        2016-04-08     AUS
3        2016-04-09     AUS
2        2016-04-15     NY
3        2016-04-15     CAN

我试图在最后一个用户的record_date和他访问过的地方的名字中访问该地点。

user_id  recorded_date_last  place_visited_most last_visited_place
    2        2016-04-15       UK                    NY
    3        2016-04-15       AUS                  CAN

2 个答案:

答案 0 :(得分:0)

这是使用子查询的一种方式:

select * ,  
    (select place_visited from mytable t2
    where t2.user_id = t1.user_id
    group by place_visited
    order by count(*) desc
    limit 1) place_visited_most
from mytable t1
where recorded_date = (select max(recorded_date) from mytable)

http://sqlfiddle.com/#!9/ad351/4

答案 1 :(得分:0)

这是一次未经测试的刺伤。我不熟悉MySQL,所以可能有其他方法可以更好地工作。这是一种基于集合的方法,可避免使用limitorder by

select t.user_id, t.place_visited, modex.cnt, maxd.max_recorded_date
from
    T t inner join
    (
        select user_id, max(recorded_date) as max_recorded_date from T
        group by user_id
    ) maxd
        on maxd.user_id = t.user_id
    inner join
    (
        select user_id, max(cnt) as max_cnt
        from
        (
            select user_id, count(*) as cnt from T
            group by user_id, place_visited
        ) counts
        group by user_id
    ) maxc
        on maxc.user_id = t.user_id
    inner join
    (
        select user_id, cnt, min(place_visited) as place_most_visited
        from
        (
            select user_id, place_visited, count(*) as cnt from T
            group by user_id, place_visited
        ) break_ties
        group by user_id, cnt
    ) modex
        on      modex.user_id = maxd.user_id
            and maxc.max_cnt = modex.cnt and modex.place_most_visited = t.place_visited

由于你可以为place_visited模式设置关系,我只是按字母顺序保持最低。我确实假设recorded_date没有联系。