这是一个类似的问题:SQL query to find status of the last event of an order
我试图找到最佳答案,但由于只有一张 table ,我什么也没得到。
本质上,我正在寻找三个查询,这些查询可以找到单个区域中的一个人、单个区域中的所有人员或所有区域中的一个人的最新状态。
这是我的表格:
表状态
ID (PK)
AreaID
PersonID
Timestamp
Status
这是输入数据:
ID AreaID PersonID Timestamp Status
1 1 1 2014-07-08 20:41:00 1
2 1 2 2014-07-08 20:42:00 1
3 1 1 2014-07-08 20:43:00 2
4 1 1 2014-07-08 20:44:00 3
5 2 3 2014-07-08 20:45:00 1
6 2 3 2014-07-08 20:46:00 2
7 1 2 2014-07-08 20:47:00 2
8 2 1 2014-07-08 20:48:00 1
如果 AreaID = 1 且 PersonID = 1,我希望第一个查询的结果如下
AreaID PersonID Timestamp Status
1 1 2014-07-08 20:44:00 3
如果 AreaID = 1,我希望第二个查询的结果如下
AreaID PersonID Timestamp Status
1 1 2014-07-08 20:44:00 3
1 2 2014-07-08 20:47:00 2
如果 PersonID = 1,我希望第三个查询的结果如下
AreaID PersonID Timestamp Status
1 1 2014-07-08 20:44:00 3
2 1 2014-07-08 20:48:00 1
如果有任何有用的帮助,我将不胜感激。谢谢。
最佳答案
假设您控制“您的 where 子句”
Select S.AreaID, S.PersonID, S.TimeStamp, S.Status
from tblStatus S
where timestamp = (
Select max(timestamp)
from TblStatus B
where S.PersonID = B.PersonID
--you need to duplicate the 'your where clauses' here too...
)
And 'your where clauses'
--在不知道表上的键的情况下,这是一个挑战,但是这种方法可以防止 where 子句重复
Select S.AreaID, S.PersonID, S.TimeStamp, S.Status
from tblStatus S
where timestamp = (
Select max(timestamp)
from TblStatus B
where S.PersonID = B.PersonID
and S.AreaID = B.AreaID
)
And 'your where clauses'
关于MySQL 查找每个区域每个人的最新状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24639985/