内部联接基于日期仅从第二个表中选择一行

时间:2019-10-14 08:30:14

标签: mysql sql oracle

我有一个用户表。每个记录在付款表中按日期都有一个或多个价格。我只是要显示一条记录,表明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  ║
╚═══════════════════════════════════╝

2 个答案:

答案 0 :(得分:1)

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>

答案 1 :(得分:0)

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

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语法(在此示例中)在聚合中保留第一个值。