I have data like so and for some reason it's just not clicking for me right now:
| cid | cmt_date | comment |
| ------------ | ------------ | ------------ |
| 1 | 2023-01-01 | LTR |
| 2 | 2023-02-01 | RTR |
Here is an example of table 2
pid | pmt_date | payment |
---|---|---|
1 | 2023-03-01 | 100 |
I would want to see the following back:
cid | comment_date | comment | pmt_date | pmt |
---|---|---|---|---|
2 | 2023-02-01 | RTR | 2023-03-01 | 100 |
Each table has about 400,000 records in them, there could be 20 records in table 1 and only 1 record in table 2.
I did something like this:
SELECT
t1.cid, t1.cmt_date AS comment_date, t1.comment,
t2.pmt_date, t2.payment AS pmt
FROM
table1 t1
INNER JOIN
table2 t2 ON t2.pmt_date > t1.cmt_date
AND t1.pt_no = t2.pt_no
pt_no
is like an invoice number and is used for a join on the same invoice.
1条答案
按热度按时间2cmtqfgy1#
You can use CROSS APPLY with a subquery to get just 1, "most recent", row from table2 for each row in table1:
Change the ordering to
ORDER BY pmt_date ASC
to get one row with the closest date to t1.cmt_date (I wasn't sure which option you wanted). You might also want to use>=
in the subquery comparison (again I can't be sure of this).