[英]SQL Select rows that have higher timestamp value
On a PostgreSQL Server i've a table like this below : 在PostgreSQL服务器上,我有一个如下表:
+------+------+------------------+
| Code | kind| timestamp |
+------+------+------------------+
| 1 | I | 16-05-2011 09:17 |
| 1 | O | 16-05-2011 09:47 |
| 2 | I | 16-05-2011 09:37 |
| 3 | I | 16-05-2011 11:26 |
| 3 | O | 16-05-2011 12:11 |
| 3 | I | 16-05-2011 13:23 |
+------+------+------------------+
This table represent IN and OUT of person in a pool with relative timestamp, and i want to know the person in the pool at a given moment. 此表表示具有相对时间戳的池中人员的IN和OUT,并且我想知道给定时刻池中的人员。
Is there a way to retrieve The row of kind 'I' that not have a corresponding 'O' ? 有没有办法检索那些没有相应'O'的'I'行? can i do it with a single Query ?
我可以用一个查询吗?
The code represent the person code ... 代码代表人员代码......
LEFT JOIN is one way to do it with LEFT JOIN是一种方法
SELECT
t.Code,
t.kind,
t.timestamp
FROM table t
LEFT JOIN table t2
ON t.code = t2.code
AND t.kind = 'I'
AND t2.kind = 'O'
WHERE t2.code IS NULL
It should be doable with Not Exists as well 它也应该与Not Exists一起使用
假设Code
是一个人,您可以将I和O kind
转换为数字+1和-1,然后选择按Code
分组的SUM(代码*种类),其总和为非零。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.