[英]How to get previous date records in SQL
I am Left joining two tables Table 1 and Table 2 on basis of invoice date & created date and also sales office Table 1 has invoice date , sales office and other columns Table 2 has created date , price and other columns so i want invoice date from table 1 and price from table 2 and for invoice date not present in created date of table 2 , I need price of previous created date from table 2 next to invoice date in output 我要根据发票日期和创建日期以及销售处将两个表Table 1和Table 2连接起来,表1包含发票日期,销售处和其他列表2已创建日期,价格和其他列,所以我要发票日期表1和表2的价格,以及对于表2的创建日期中不存在的发票日期,我需要输出中发票日期旁边的表2的先前创建日期的价格
Table 1 表格1
invoice date sales office
01-04-2019 ABC
02-04-2019 ABC
04-04-2019 ABC
06-04-2019 ABC
Table 2 表2
created date sales office price
01-04-2019 ABC 10
02-04-2019 ABC 20
05-04-2019 ABC 30
07-04-2019 ABC 30
Output 输出量
Invoice date New date price
01-04-2019 01-04-2019 10
02-04-2019 02-04-2019 20
04-04-2019 02-04-2019 20
06-04-2019 05-04-2019 30
If you want the most recent price for each invoice, then you can use a lateral join or correlated subquery: 如果您需要每个发票的最新价格,则可以使用横向联接或相关子查询:
select i.invoicedate, p.createddate, p.price
from invoices i outer apply
(select top (1) p.*
from prices p
where p.salesoffice = i.salesoffice and
p.createddate <= i.invoicedate
order by p.createddate desc
) p;
In other databases, you can use window functions: 在其他数据库中,可以使用窗口函数:
select ip.*
from (select i.invoicedate, p.createddate, p.price,
row_number() over (partition by i.invoicedate order by p.createddate desc) as seqnum
from invoices i join
prices p
on p.salesoffice = i.salesoffice and
p.createddate <= i.invoicedate
) ip
where seqnum = 1;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.