首页 > 解决方案 > 如何根据另一个选择类的结果值在选择类中添加条件

问题描述

我有查询获取“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;
  1. 来自同一个 sol_pro 表的 B_value 和 B_date,
  2. 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

标签: postgresql

解决方案


假设您有表usersmeasures

# 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 BYPS使用子句时必须仔细对表行进行排序,DISTINCT ON ()因为 PostgreSQL 将只保留第一条记录并丢弃其他记录。


推荐阅读