首页 > 解决方案 > 如何在mysql中生成价格比较报告

问题描述

我有一个过时的布伦特价格表,其中包含从 1 月 1 日到 1 月 31 日的价目表。我想将 2020 年 1 月 1 日(或其他日期)的价格与 2021 年 1 月 1 日(或其他日期)的价格进行比较,报告将包含日期、年份,如 2020 年和 2021 年,2020 年的价格显示在 2020 年和2021 年的价格显示在 2021 年之下。我已经编写了以下查询,但没有。

SELECT b.date
     , b1.price as year1
     , b2.price as year2 
  from brentprices as b 
  join brentprices as b1 
    on b1.year = '2020'
  join brentprices as b2 
    on b2.year = '2021'

下面是样本表和数据

在此处输入图像描述

下面是预期的结果

在此处输入图像描述

标签: mysqlsql

解决方案


tabular text并且images是不同的......(但这是另一个讨论):

create table brentprices (date date primary key, price decimal(8.2));

insert into brentprices values ('2020-01-01', 100);
insert into brentprices values ('2020-01-02', 101);
insert into brentprices values ('2020-01-03', 102);
insert into brentprices values ('2021-01-01',  99);
insert into brentprices values ('2021-01-02', 103);
insert into brentprices values ('2021-01-03', 102);

select * 
from brentprices b1 
left join brentprices b2 on b2.date=date_add(b1.date,INTERVAL 1 YEAR) 
where year(b1.date)=2020;

输出:

+------------+-------+------------+-------+
| date       | price | date       | price |
+------------+-------+------------+-------+
| 2020-01-01 |   100 | 2021-01-01 |    99 |
| 2020-01-02 |   101 | 2021-01-02 |   103 |
| 2020-01-03 |   102 | 2021-01-03 |   102 |
+------------+-------+------------+-------+

推荐阅读