dongyou2635 2013-07-29 09:37
浏览 143
已采纳

使用MAX和GROUP BY从表中提取数据

I'm trying to pull data out from a table. To simplify I have a table (time_entries ) has 3 colums user_name, entry_type and entry_datetime

Here is a sample output

user_name| entry_type   | entry_datetime
 User1   |   Time In    | 28-JUL-13  16:40:40
 User1   |   Time Out   | 28-JUL-13  16:40:41
 User2   |   Time In    | 28-JUL-13  16:41:13
 User2   |   Time Out   | 28-JUL-13  16:41:15
 User3   |   Time In    | 28-JUL-13  16:42:32

What I'm trying to do here is to pull the result when the last time each User logged in

MY QUERY

SELECT te.user_name, te.entry_type,  MAX(te.entry_datetime) AS date
FROM time_entries AS te
GROUP BY te.user_name 

this runs fine only with wrong results, here is the output below

OUTPUT

user_name| entry_type | entry_datetime
User1    | Time In    | 28-JUL-13 16:40:41
User2    | Time In    | 28-JUL-13 16:41:15
User3    | Time In    | 28-JUL-13 16:42:32

user_name and entry_datetime is correct but the entry_type are all Time In. User1 and User2 entry_type must be Time Out.

Anyone knows a solution for this problem?

  • 写回答

3条回答 默认 最新

  • doulian7252 2013-07-29 09:45
    关注

    You can use a filtering join to list the latest entry per user:

    select  *
    from    time_entries te
    join    (
            select  user_name
            ,       max(entry_datetime) as maxdt
            from    time_entries
            group by
                    user_name
            ) filter
    on      filter.user_name = te.user_name
            and filter.maxdt = te.entry_datetime
    

    Working example at SQL Fiddle.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)