-1
+--------+------+---------------------+
| userId | Cmd  | Time                |
+--------+------+---------------------+
|      1 |  A   | 2013-06-21 13:15:08 |
|      1 |  B   | 2013-07-31 15:58:53 |
|      3 |  A   | 2013-07-31 16:01:42 |
|      4 |  A   | 2013-05-01 11:05:08 |
|      4 |  B   | 2013-07-31 16:06:32 |
|      6 |  B   | 2013-07-31 17:16:08 |
|      7 |  A   | 2013-04-06 17:20:36 |
|      3 |  B   | 2013-04-15 06:26:14 |
|      7 |  B   | 2013-07-31 14:53:49 |
|      6 |  A   | 2013-07-31 09:56:27 |
+--------+------+---------------------+

How to get userIDs where their last Cmd is B?

Expected result:

+--------+------+---------------------+
| userId | Cmd  | Time                |
+--------+------+---------------------+
|      1 |  B   | 2013-07-31 15:58:53 |
|      4 |  B   | 2013-07-31 16:06:32 |
|      6 |  B   | 2013-07-31 17:16:08 |
|      7 |  B   | 2013-07-31 14:53:49 |
+--------+------+---------------------+
4

4 回答 4

2

Here you need to self join using MAX(Time), UserId and Cmd='B' like this:

SELECT t1.* FROM Table1 t1
JOIN
(
   SELECT UserId, MAX(Time) MaxTime FROM Table1
   GROUP BY UserID
)t2
ON t1.UserID = t2.UserId
AND t1.Time = t2.MaxTime
AND t1.Cmd = 'B';

Output:

| USERID | CMD |                        TIME |
----------------------------------------------
|      1 |   B | July, 31 2013 15:58:53+0000 |
|      4 |   B | July, 31 2013 16:06:32+0000 |
|      6 |   B | July, 31 2013 17:16:08+0000 |
|      7 |   B | July, 31 2013 14:53:49+0000 |

See this SQLFiddle

于 2013-08-14T06:32:37.000 回答
1

首先获取每个 Cmd 的最后日期,然后选择与该日期匹配的记录:

SELECT userId
FROM SomeTable
JOIN ( SELECT Cmd,
              MAX(Time) AS MaxTime
       FROM SomeTable
       GROUP BY Cmd
     ) MaxTable ON SomeTable.Cmd = MaxTable.Cmd
               AND SomeTable.Time = MaxTable.MaxTime

如果您只想要 B 记录:

SELECT userId
FROM SomeTable
JOIN ( SELECT Cmd,
              MAX(Time) AS MaxTime
       FROM SomeTable
       GROUP BY Cmd
       WHERE Cmd = 'B'
     ) MaxTable ON SomeTable.Cmd = MaxTable.Cmd
               AND SomeTable.Time = MaxTable.MaxTime

编辑: 误解了这个问题。请参阅 hiss056 的答案。他正在做和我一样的事情,但在 UserId 而不是 Cmd 上进行分组。相比:

SELECT SomeTable.*
FROM SomeTable
JOIN ( SELECT userId,
              MAX(Time) AS MaxTime
       FROM SomeTable
       GROUP BY userId

     ) MaxTable ON SomeTable.userId= MaxTable.userId
               AND SomeTable.Time = MaxTable.MaxTime
WHERE SomeTable.Cmd = 'B'
于 2013-08-14T06:08:46.330 回答
0

查询是:

SELECT userID
FROM TABLE_COMMANDE
WHERE 
(
 TIME = (SELECT MAX(TIME) FROM TABLE_COMMANDE WHERE CMD LIKE 'B')
)
于 2013-08-27T09:54:01.713 回答
-1
select userID
from your_table
where CMD like 'B'
于 2013-08-14T06:00:55.317 回答