开发者

SQL Select rows that have higher timestamp value

On a PostgreSQL Server i've a table like this below :

+------+------+------------------+
| 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.

Is there a way to retrieve The row of kind 'I' that not have a corresponding 'O' ? can开发者_JS百科 i do it with a single Query ?

The code represent the person code ...


LEFT JOIN is one way to do it with

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


Assuming Code is a person, you could convert kind I and O to numbers +1 and -1, then select SUM(Code*kind), grouped by Code, having the sum being nonzero.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜