postgresql - 如何根据另一个选择类的结果值在选择类中添加条件
问题描述
- 我需要一个 Postgres 查询来获取“A 值”、“A 值日”、“B 值”和“B 值日”
- B 值和日期应为“A 值日期”的 95 至 100 天之间的一个
我有查询获取“A 值”和“A 值日期”,不知道如何使用结果(A 值)获取 B 值和日期
select u.id,
(select activity
from Sol_pro
where user_id = u.id
and uni_par = 'weight_m'
order by created_at asc
limit 1) as A_value
from users u;
- 来自同一个 sol_pro 表的 B_value 和 B_date,
- A_value 日期后 95-100 天(如果在 95-100 之间有更多,我只需要一个(最近的)值)预期
输出: id = 112233,A_Value = "weight = 210.25",A_value_date = 12-12-2020,B_value = "weight = 220.25",B_value_date = 12-12-2020
解决方案
假设您有表users
和measures
:
# create table users (id integer);
# create table measures (user_id integer, value decimal, created_at date);
它们充满了测试数据:
INSERT INTO users VALUES (1), (2), (3);
INSERT INTO measures VALUES (1, 100, '9/10/2020'), (1, 103, '9/15/2020'), (1, 104, '10/2/2020');
INSERT INTO measures VALUES (2, 200, '9/11/2020'), (2, 207, '9/21/2020'), (2, 204, '10/1/2020');
INSERT INTO measures VALUES (3, 300, '9/12/2020'), (3, 301, '10/1/2020'), (3, 318, '10/12/2020');
询问:
WITH M AS (
SELECT
A.user_id,
A.value AS A_value, A.created_at AS A_date,
B.value AS B_value, B.created_at AS B_date
FROM measures A
LEFT JOIN measures B ON
A.user_id = B.user_id AND
B.created_at >= A.created_at + INTERVAL '5 days' AND
B.created_at <= A.created_at + INTERVAL '10 days'
ORDER BY
user_id, A_date, B_date
)
SELECT DISTINCT ON (user_id) * FROM M;
将为每个用户选择:
- 第一个可用的测量值 (A)
- 下一次测量 (B) 是在 (A) 的 5-10 天之间进行的。
结果:
user_id | a_value | a_date | b_value | b_date
---------+---------+------------+---------+------------
1 | 100 | 2020-09-10 | 103 | 2020-09-15
2 | 200 | 2020-09-11 | 207 | 2020-09-21
3 | 300 | 2020-09-12 | [NULL] | [NULL]
(3 rows)
ODRDER BY
PS使用子句时必须仔细对表行进行排序,DISTINCT ON ()
因为 PostgreSQL 将只保留第一条记录并丢弃其他记录。
推荐阅读
- javascript - 如何让这个函数在两个 $.getJSON 函数之后发生?
- java - 无法在 VScode 中创建 Maven 项目:“程序 'cmd' 运行失败”
- swiftui - 如何制作一个按钮来关闭使用 UIHostingController/SwiftUI 呈现的视图?
- javascript - 如何在没有href但使用内容和url属性的新窗口中打开url
- javascript - 剃须刀页面 DropDownListFor; 如何为下拉列表中的每个项目设置不同的背景颜色?
- google-bigquery - 检查您离 Google Big Query 的距离太近了
- vulkan - 为交换链选择表面格式?
- r - 在 spatstat 中使用 sf 多边形对象作为窗口
- c# - 从 odata RawValues 中提取字符串列表
- java - status":500,"error":"内部服务器错误(Spring Boot 和 cURL)