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条)

报告相同问题?

悬赏问题

  • ¥50 随机森林与房贷信用风险模型
  • ¥50 buildozer打包kivy app失败
  • ¥30 在vs2022里运行python代码
  • ¥15 不同尺寸货物如何寻找合适的包装箱型谱
  • ¥15 求解 yolo算法问题
  • ¥15 虚拟机打包apk出现错误
  • ¥15 用visual studi code完成html页面
  • ¥15 聚类分析或者python进行数据分析
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备