繁体   English   中英

选择相对于另一个表的最新日期

[英]Selecting Most Recent Date Relative to Another Table

只是为此而烦恼...

我在mysql中有两个表,并且满足以下条件时,我需要从表A中获取记录:1)表A中的名称与表B中的名称匹配并且2)表B中最近一天的价格低于表A中的记录

因此...在下面的示例表上运行查询将获取以下两条记录:

03-17-2019    Bob   8
03-20-2019    John  10

本质上,我需要评估表A中的每一行,检查表B中具有相对于表A中所评估记录最近日期的匹配名称,然后确定表A中的价格是否大于价格。表B中最新的匹配名称。此后,我需要计算价格之间的差异。 因此,在上面的两个记录中,差异将为2和4

Table A
Date       | Name | Price
03-08-2019    Bob   6
03-25-2019    Bob   2
03-17-2019    Bob   8
03-20-2019    John  10

Table B
Date      | Name  |  Price
03-16-2019    Bob   4
03-28-2019    Bob   9
03-02-2019    Bob   12
03-10-2019    John  6

感谢您的帮助!

联接两次表,一次获得最小日期差,然后获得具有最小日期差的行:

select a.*
from tablea a 
inner join tableb b on b.name = a.name 
inner join (
  select a.name, min(abs(datediff(b.date, a.date))) mindatediff
  from tablea a inner join tableb b
  on b.name = a.name
  group by a.name           
) g on g.name = a.name and abs(datediff(b.date, a.date)) = g.mindatediff

参见演示
要么:

select a.*
from tablea a inner join tableb b
on b.name = a.name
where abs(datediff(b.date, a.date)) = (
    select min(abs(datediff(x.date, y.date))) 
    from tablea x inner join tableb y
    where x.name = a.name and y.name = b.name                            
)

参见演示
结果:

| date       | name | price |
| ---------- | ---- | ----- |
| 2019-03-17 | Bob  | 8     |
| 2019-03-20 | John | 10    |

在MySQL 8+中,您将使用窗口函数

select ab.*, (price - b_price)
from (select a.*, b.price as b_price,
             row_number() over (partition by a.name order by datediff(b.date, a.date) as seqnum
      from a join
           b
           on a.name = b.name and
              a.date >= b.date
     ) ab
where seqnum = 1;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM