简体   繁体   English

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

[英]Pulling data from a table using MAX and 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 为简化起见,我有一个表(time_entries)有3个列user_name,entry_type和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. user_name和entry_datetime是正确的,但entry_type均为“ Time In”。 User1 and User2 entry_type must be Time Out. User1和User2 entry_type必须为超时。

Anyone knows a solution for this problem? 有人知道这个问题的解决方案吗?

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. SQL Fiddle的工作示例。

I haven't tested this, but it may be something like this 我没有测试过,但是可能是这样的

SELECT 
   te.user_name as name, 
   MAX(te.entry_datetime) AS date, 
   (SELECT te2.entry_type 
       FROM time_entries AS te2 
       WHERE te2.user_name = name AND te2.entry_datetime = date)
FROM 
   time_entries AS te
GROUP BY 
   te.user_name 

Try this... 尝试这个...

SELECT te.user_name, te.entry_type,  te.entry_datetime
FROM time_entries AS te
WHERE te.entry_datetime IN (SELECT MAX(te2.entry_datetime)
                            FROM FROM time_entries AS te2
                            WHERE te2.user_name = te.user_name)

This assumes that there will not be entries with duplicate values of entry_datetime 假设不会有条目具有重复的entry_datetime值

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM