我有一个SQL表格如下:
id | timestamp | position | size | level
id
是主键,并且始终具有值timestamp
是一个数字时间表示position
,size
和level
可能有值,或者可能为null 我想执行一个查询,它将获得最新的非空位置,大小和级别,由它所属的行中的时间戳决定。
我该怎么做?
答案 0 :(得分:3)
SELECT t.*
FROM yourTable t
WHERE t.timestamp = (SELECT MAX(timestamp) FROM yourTable WHERE position IS NOT NULL)
如果您还想在查找最大时间戳时为NULL
和size
列强制执行非level
值,则可以使用以下子查询:
SELECT MAX(timestamp) FROM yourTable WHERE position IS NOT NULL AND
size IS NOT NULL AND
level IS NOT NULL
答案 1 :(得分:1)
如果您要查找不同行中的值,则可以执行以下操作:
select (select position
from t
where position is not null
order by timestamp desc
fetch first 1 row only
) as position,
(select size
from t
where size is not null
order by timestamp desc
fetch first 1 row only
) as size,
(select level
from t
where level is not null
order by timestamp desc
fetch first 1 row only
) as level;
注意:这是(几乎完全)标准SQL。确切的语法可能因您使用的数据库而异。