mysql - 如何在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'
下面是样本表和数据
下面是预期的结果
解决方案
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 |
+------------+-------+------------+-------+
推荐阅读
- ios - 离子 4 ios: libsystem_kernel.dylib`__abort_with_payload:
- c++ - 实现“-”运算符重载作为类的友元函数
- reactjs - 是否可以在使用 npm 的反应 js 中使用 Material Design for Bootstrap?
- html - 将插槽传递到 Vue.js 中的插槽
- python - 仅当我在 php 中执行 python 程序时才发生 Python 导入错误
- python - 如何获得学期平均值
- ansible - Mikrotik 操作系统命令
- c - GTK3.0+ App UI 冻结问题。线程问题
- jquery - 如何在不刷新整个页面的情况下在 PHP/WordPress 中执行切换功能 jQuery?
- ios - (Swift) 如何在一个文件夹中创建子文件夹