-1

我有下表:

+--+--------------------+---------+---- ------------------+
|身份证| lt_user | lt_time_stamp | lt_activity_operation |
+--+--------------------+---------+---- ------------------+
|1 | 对外销售 | 2013-02-15 15:17:34 | 登录 |
|2 | 对外销售 | 2013-03-20 16:25:09 | 登录 |
|3 | 内部销售 | 2013-07-29 13:09:22 | 登录 |
|4 | 内部销售 | 2013-08-01 11:06:11 | 登录 |
|5 | 内部销售 | 2013-08-02 10:06:59 | 登录 |
|6 | 内部销售| 2013-08-02 10:21:38 | 登录 |
|7 | 内部销售| 2013-08-07 16:13:01 | 登录 |
|8 | 内部销售 | 2013-08-12 10:51:16 | 登录 |
+--+--------------------+---------+---- ------------------+

我试图检索每个用户的最后一个实例(时间戳)一次。

我需要的是:

+--+--------------------+---------+---- ------------------+
|身份证| lt_user | lt_time_stamp | lt_activity_operation |
+--+--------------------+---------+---- ------------------+
|2 | 对外销售 | 2013-03-20 16:25:09 | 登录 |
|8 | 内部销售 | 2013-08-12 10:51:16 | 登录 |
+--+--------------------+---------+---- ------------------+

我得到的是:

+--+--------------------+---------+---- ------------------+
|身份证| lt_user | lt_time_stamp | lt_activity_operation |
+--+--------------------+---------+---- ------------------+
|3 | 内部销售 | 2013-07-29 13:09:22 | 登录 |
|1 | 对外销售 | 2013-02-15 15:17:34 | 登录 |
+--+--------------------+---------+---- ------------------+

我的查询是:

SELECT lt_user, lt_time_stamp, lt_activity_operation
  FROM log_table
 GROUP BY lt_user
 ORDER BY lt_time_stamp DESC;

谢谢

4

5 回答 5

1

尝试使用MAX()

SELECT lt_user, MAX(lt_time_stamp), lt_activity_operation 
FROM log_table GROUP BY lt_user, lt_activity_operation;

看到这个 SQLFiddle

于 2013-08-23T11:02:56.960 回答
0

限制版本:

SELECT lt_user, lt_time_stamp, lt_activity_operation 
FROM log_table GROUP BY lt_user, lt_activity_operation 
ORDER BY lt_time_stamp DESC LIMIT 1;
于 2013-08-23T11:05:41.333 回答
0

获取最后一行的正确方法是进行聚合以获取max()值,然后连接回原始数据:

select lt.*
from (SELECT lt_user, max(lt_time_stamp) as maxts
      FROM log_table
      GROUP BY lt_user 
     ) ltsum join
     log_table lt
     on ltsum.lt_user = lt.user and ltsum.maxts = lt.lt_time_stamp;

在这种情况下,您只需要获取最后一个活动。你也可以用这个技巧来做到这一点:

SELECT lt_user, max(lt_time_stamp) as maxts,
       substring_index(group_concat(lt_activity_operation order by lt_time_stamp desc), ',', 1
                      ) as last_activity
FROM log_table
GROUP BY lt_user;
于 2013-08-23T11:09:19.527 回答
0

像这样使用

SELECT lt_user, MAX(lt_time_stamp), lt_activity_operation FROM log_table GROUP BY lt_user, lt_activity_operation ORDER BY lt_time_stamp DESC;

于 2013-08-23T11:25:36.950 回答
0

使用该GROUP BY命令时,您需要告诉 SQL 应该显示所有选择的记录中的哪一条,因为它需要所有这些记录并将它们分组到每个分组记录的一个结果记录中。因此,您需要为其选择MAX()或任何其他特定函数或参数(在您的情况下为时间戳)。

    SELECT lt_user, MAX(lt_time_stamp), lt_activity_operation
      FROM log_table
     GROUP BY lt_user
     ORDER BY lt_time_stamp DESC;

lt_activity_operation如果列都相同(在您的数据库中登录),则列不需要函数,但可能需要以与 lt_time_stamp 相同的方式选择它。

于 2015-10-29T19:21:49.823 回答