簡體   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