我在从一个表中的单个字段获取两个表中的数据时遇到问题。两个表中都不存在该字段。
示例:
invoice email customer_name original_bill invoice_status
1 a@g.com bob 5.00 P
2 a@g.com harry 23.00 P
3 a@g.com sally 4.00 P
4 b@g.com loretta 14.00 P
5 b@g.com hamish 74.00 P
invoice email date_last_modified_timestamp mod_status mod_amount
1 a@g.com 2019-05-01 A 3.00
1 a@g.com 2019-04-01 D
3 b@g.com 2019-10-25 A
所有违规行为及其Mod的列表,但我只希望每张发票在列表中出现一次。根据表二中的最新日期。
示例:
invoice email customer_name original_bill invoice_status date_last_modified_timestamp mod_status mod_amount
1 a@g.com bob 5.00 P 2019-05-01 A 3.00
2 a@g.com harry 23.00 P
3 a@g.com sally 4.00 P 2019-10-25 A
4 b@g.com loretta 14.00 P
5 b@g.com hamish 74.00 P
我现在如何拉动它:
select invoice, email, customer_name, original bill, invoice status, max(date_last_modified_timestamp), mod status, mod_amount
from table one
left join on table1.invoice = table 2.invoice
group by
invoice, email, customer_name, original bill, invoice status, max(date_last_modified_timestamp), mod status, mod_amount
我尝试了无数次的变奏。
答案 0 :(得分:0)
您可以加入并使用相关的子查询进行过滤:
select i.*, e.*
from invoices i
inner join customer_invoice_edits e
on e.invoice = i.invoice
and e.date_last_modified_timestamp = (
select max(date_last_modified_timestamp)
from customer_invoice_edits e1
where e1.invoice = e.invoice
)
这将为您提供invoices
表中每行一条记录,该记录在customer_invoice_edits
中具有匹配项,在customer_invoice_edits
中具有最新的对应记录。
如果某些发票在从属表中没有对应的记录,它们将不会出现在结果集中。如果您确实想看到它们,则可以改用left join
。
答案 1 :(得分:0)
这是您想要的吗?
select
invoice,
email
from (
select
invoice,
email,
mod_status,
mod_amount,
date_last_modified_timestamp,
row_number() over (
partition by invoice, email
order by date_last_modified_timestamp desc
) rn
from table2
)
where rn=1
答案 2 :(得分:0)
我很确定您想要逐个字段。这是一个示例:
select i.invoice,
nz( (select top (1)
from invoice_edits as ie
where ie.invoice = i.invoice and ie.email is not null
), i.email
) as email,
nz( (select top (1)
from invoice_edits as ie
where ie.invoice = i.invoice and ie.mod_amount is not null
), i.original_bill
) as original_bill,
. . .
from invoices as i;