繁体   English   中英

内连接 select 仅从第二个表中的一行基于日期

[英]inner join select only one row from second table base on date

我有一个用户表。 每条记录在付款表中都有一个或多个按日期排列的价格。 我只是要显示一条start_date列小于或等于今天的记录?

用户表

╔════╦══════════════╗
║ id ║  name        ║
╠════╬══════════════║
║  1 ║ Jeff         ║
║  2 ║ Geoff        ║
╚════╩══════════════╝

付款表

╔═══════════════════════════════════╗
║ user_id         start_date  price ║
╠═══════════════════════════════════╣
║ 1               2019-10-14  1000  ║
║ 1               2019-10-11  3500  ║
║ 1               2019-10-16  2000  ║
║ 2               2019-10-13  3500  ║
║ 2               2019-10-12  6500  ║
╚═══════════════════════════════════╝

今天日期 => 2019-10-13

我想要的是:

╔═══════════════════════════════════╗
║ user_id         start_date  price ║
╠═══════════════════════════════════╣
║ 1               2019-10-11  3500  ║
║ 2               2019-10-13  3500  ║
╚═══════════════════════════════════╝
where date_column <= sysdate

或者,最终

where date_column <= trunc(sysdate)

取决于是否涉及时间组件。

[编辑,包含样本数据后]

由于“今天”是2019-10-13 ,那么看看这是否有帮助; 你需要从 #14 开始的行,因为你已经有了这些表。 顺便说一句,似乎USERS在期望的结果中没有任何作用。

SQL> with
  2  users (id, name) as
  3    (select 1, 'Jeff' from dual union all
  4     select 2, 'Geoff' from dual
  5    ),
  6  payments (user_id, start_date, price) as
  7    (select 1, date '2019-10-14', 1000 from dual union all
  8     select 1, date '2019-10-11', 3500 from dual union all
  9     select 1, date '2019-10-16', 2000 from dual union all
 10     select 2, date '2019-10-13', 3500 from dual union all
 11     select 2, date '2019-10-12', 6500 from dual
 12    ),
 13  --
 14  temp as
 15    (select p.user_id, p.start_date, p.price,
 16       row_number() over (partition by user_id order by start_date desc) rn
 17     from payments p
 18     where p.start_date <= date '2019-10-13'
 19    )
 20  select user_id, start_date, price
 21  from temp
 22  where rn = 1;

   USER_ID START_DATE      PRICE
---------- ---------- ----------
         1 2019-10-11       3500
         2 2019-10-13       3500

SQL>

一种方法使用相关子查询:

select p.*
from payments p
where p.date = (select max(p2.start_date)
                from payments p2
                where p2.user_id = p.user_id and
                      p2.start_date <= date '2019-10-13'
               );

或者在 Oracle 中,您可以使用聚合并keep

select p.user_id, max(p.start_date) as start_date,
       max(p.price) keep (dense_rank first order by p.start_date desc) as price
from payments p
group by p.user_id;

keep语法(在本例中)是保留聚合中的第一个值。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM