[英]SQL - Query latest value from table for each match
I have 2 tables, similar to this: 我有2张桌子,类似于:
Person:
id
name
HeightStatus:
timestamp // The time that this status is relevant to
person_id
height
Possible values can be 可能的值可以是
Person - [1, John], [2, Bob], [3, Jeniffer] 人-[1,John],[2,Bob],[3,Jeniffer]
HeightStatus - [100, 1, 5], [150, 1, 7], [40, 2, 12], [30, 2, 9], [400, 3, 7] HeightStatus-[100,1,5],[150,1,7],[40,2,12],[30,2,9],[400,3,7]
This means that I have 3 persons, and on time 100, john's height was 5, at time 150 his height was 7 and so on 这意味着我有3个人,在时间100,约翰的身高是5,在时间150,他的身高是7,依此类推。
querying the latest height of a specific person is easy (for example for the person with id 1): 查询特定人员的最新身高很容易(例如ID为1的人员):
select height
from Person, HeightStatus
where Person.id==HeightStatus.person_id and Person.id == 1
order by timestamp desc
limit 1
My problem is how to use that as part of a larger query? 我的问题是如何在更大的查询中使用它?
eg - I want to get all the people that their latest height is greater than 8 例如-我想让所有人的最新身高大于8
I guess it is possible to use a view or just use a query within a query. 我猜有可能使用视图或只在查询中使用查询。
I'm using Django, but I'm open to writing that as a plain SQL query and necessarily using Django's ORM 我正在使用Django,但我愿意将其编写为普通的SQL查询,并且必须使用Django的ORM
I would just use a correlated subquery: 我将只使用一个相关的子查询:
select hs.*
from heightstatus hs
where hs.timestamp = (select max(hs2.timestamp) from heightstatus hs2 where hs2.person_id = hs.person_id);
If you're using Sqlite 3.25 or newer, window functions allow for an elegant solution: 如果您使用的是Sqlite 3.25或更高版本,则窗口函数可提供一种优雅的解决方案:
WITH bytimes AS (SELECT id, name, timestamp, height
, rank() OVER (PARTITION BY id ORDER BY timestamp DESC) AS rank
FROM person JOIN heightstatus ON id = person_id)
SELECT * FROM bytimes WHERE rank = 1 AND height > 8;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.