获取日期范围内的最大数据,无需重复MYSQL

时间:2013-03-28 01:40:13

标签: mysql sql group-by between

我在查询时遇到了麻烦。

SELECT * FROM YourTable AS T1
INNER JOIN
(SELECT user_id , MIN(some_timestamp)  AS some_timestamp FROM YourTable
GROUP BY user_id) AS T2
ON T1.User_Id = T2.User_Id AND T1.some_timestamp = T2.some_timestamp
WHERE Some_Timestamp BETWEEN '13-Jun-12 08:00' AND '13-Jun-12 10:00'

表名:YourTable


| PK_ID | USER_ID |  SOME_TIMESTAMP |
------------------------------------|
|     1 |     123 | 13-Jun-12 14:30 |
|     2 |     123 | 13-Jun-12 08:50 |
|     3 |     567 | 13-Jun-12 09:23 |
|     4 |     567 | 13-Jun-12 09:45 |
|     5 |     567 | 13-Jun-12 09:40 |
|     6 |     890 | 13-Jun-12 08:44 |   

我想得的是这样的1。从[13-Jun-12 08:00]之间的特定日期范围获取数据[13-Jun-12 10:00]
2。一旦它在范围内获取日期,它将获取没有重复的最新日期。

输出应该是这样的:
1.日期范围

[13-Jun-12 08:00] & [13-Jun-12 10:00]

2.仅获取没有重复项的最新时间戳。

结果应该是这样的



| PK_ID | USER_ID |  SOME_TIMESTAMP |
------------------------------------|
|     2 |     123 | 13-Jun-12 08:50 |
|     4 |     567 | 13-Jun-12 09:45 |
|     6 |     890 | 13-Jun-12 08:44 |

非常感谢大家!

3 个答案:

答案 0 :(得分:4)

SELECT 
    pk_id,
    user_id,
    MAX(some_timestamp)
FROM
    your_table
WHERE
    some_timestamp>= '13-Jun-12 08:00' 
AND some_timestamp<= '13-Jun-12 10:00'
GROUP BY
    user_id
ORDER BY
    pk_id ASC

SQL Fiddle

答案 1 :(得分:1)

您的查询非常接近。需要选择MAX而不是MIN,并且需要将WHERE条件移到子查询中:

SELECT * 
FROM YourTable AS T1
  INNER JOIN
  (SELECT user_id , MAX(some_timestamp)  AS some_timestamp 
   FROM YourTable
  WHERE Some_Timestamp BETWEEN '2013-06-12 08:00' AND '2013-06-12 10:00'
   GROUP BY user_id) AS T2
    ON T1.User_Id = T2.User_Id AND T1.some_timestamp = T2.some_timestamp

SQL Fiddle Demo

返回:

PK_ID    USER_ID   SOME_TIMESTAMP
2        123       June, 12 2013 08:50
4        567       June, 12 2013 09:45
6        890       June, 12 2013 08:44

根据需要格式化SOME_TIMESTAMP字段。我还建议您使用>=<=代替BETWEEN,因为您可能无法通过BETWEEN获得所需的结果。

答案 2 :(得分:0)

我想你在最大时间戳时想要pk_id

要在MySQL中执行此操作,您通常必须重新加入原始数据。但在您的情况下,似乎pk_id正在增加以增加时间戳。如果这是真的,那么以下查询应返回您想要的内容:

select max(pk_id) as pk_id, user_id, max(some_timestamp)
FROM your_table
WHERE Some_Timestamp between '13-Jun-12 08:00' AND Some_Timestamp <= '13-Jun-12 10:00'
GROUP BY user_id
ORDER BY pk_id ASC

如果您不包含max(pk_id),则会返回任意pk_id,这与最大时间戳无关。