sql - 需要一个 SQL 查询,该查询将与另一个表连接,该表又将根据时间返回最新值,分组为一行
问题描述
我需要有关 SELECT SQL 查询的帮助,该查询将与 id 列上的另一个表连接,这又将根据时间返回最新值,分组为一行?
基本上,以这样一种方式连接两个表,即对于存在于 time_series 表中的 users 表中的每条记录,返回基于时间分组到单行中的最新值。
用户表:
id | name
----+--------
1 | "Joe"
2 | "Ron"
时间序列表:
time| id | a | b | c | d
----+-----+-----+-----+----+----
1 | 1 | a1 | | |
2 | 1 | | b1 | |
3 | 1 | | | c0 |
4 | 1 | a3 | | c3 |
5 | 1 | a0 | | |
6 | 2 | a3 | | c3 | d1
7 | 2 | a2 | | | d3
结果应如下所示:
id | a | b | c | d | name
----+-----+-----+----+----+------
1 | a0 | b1 | c3 | | "Joe"
2 | a2 | | | d3 | "Ron"
解决方案
一个选项使用几个子查询:
select u.*,
(select ts.a from time_series ts where ts.id = u.id and ts.a is not null order by ts.time desc limit 1) a,
(select ts.b from time_series ts where ts.id = u.id and ts.b is not null order by ts.time desc limit 1) b,
(select ts.c from time_series ts where ts.id = u.id and ts.c is not null order by ts.time desc limit 1) c,
(select ts.d from time_series ts where ts.id = u.id and ts.d is not null order by ts.time desc limit 1) d
from users u
另一种解决方案是对每一列的行进行排名row_number()
,优先考虑非null
值,然后是条件聚合:
select u.id,
max(case when ts.rn_a = 1 then ts.a end) a,
max(case when ts.rn_b = 1 then ts.b end) a,
max(case when ts.rn_c = 1 then ts.c end) a,
max(case when ts.rn_d = 1 then ts.d end) d
from users u
inner join (
select ts.*,
row_number() over(order by (case when a is null then 1 else 0 end), time desc) rn_a,
row_number() over(order by (case when b is null then 1 else 0 end), time desc) rn_b,
row_number() over(order by (case when c is null then 1 else 0 end), time desc) rn_c,
row_number() over(order by (case when d is null then 1 else 0 end), time desc) rn_d
from time_series ts
) ts on ts.id = u.id
group by u.id
推荐阅读
- oop - 如何在飞镖/颤振中使用子类作为父类类型?
- excel - Excel AGGREGATE 函数:应用布尔数组乘法时出现#VALUE 错误
- google-maps - 有没有办法找到谷歌地图缩短链接的目标网址并使用谷歌应用脚本提取纬度和经度?
- c# - 如何按键转换 TabItem 以读取 ChildNames
- reactjs - 在 spfx react 项目中使用 domElement 和 pageContext 有什么区别?
- html - 如何将组件添加到css max-width,height计算?
- javascript - 如何对 jquery 数据表中的数据应用过滤器?
- apache-kafka - 使用rest API安装连接器到kafka connect
- python - 无法设置子类的属性
- c++ - 比较文本文件的元素