[英]Special join of two tables using date range
我的论文使用的 MariaDB 数据库中有两张表,一张是金融公司年数,一张是专利数据。 专利数据表(表 A)看起来像
Company | Publication_number | Application_Date | Document_Type | Country_Code | ...
A | US2019xxxx | 2018-12-01 | application | US | ...
A | WO2018xxxx | 2018-12-01 | application | WO | ...
A | US2018xxxx | 2017-09-23 | application | WO | ...
B | EP3285xxxx | 2018-09-23 | patent | EP | ...
B | US2019xxxx | 2019-01-27 | patent | EP | ...
...
财务年度表(表 B)如下所示:
Company | Financial_Year | Financial_Year_Start | Financial_Year_End
A | 2018 | 2018-01-01 | 2018-12-31
A | 2017 | 2017-01-01 | 2017-12-31
B | 2018 | 2018-04-01 | 2019-03-31
...
我想要的是一张表(表C),例如:
Company | Publication number | Application Date | Financial Year | Document Type | Country Code | ...
A | US2019xxxx | 2018-12-01 | 2018 | application | US | ...
A | WO2018xxxx | 2018-12-01 | 2018 | application | WO | ...
A | US2016xxxx | 2017-09-23 | 2017 | application | WO | ...
B | EP3285xxxx | 2018-09-23 | 2018 | patent | EP | ...
B | US2019xxxx | 2019-01-27 | 2018 | patent | EP | ...
...
似乎很容易,但我还没有找到一种方法来使用开始和结束日期正确分配财政年度。 不幸的是,财政年并不总是与日历年重合。 谁能告诉我如何解决这个问题? 我的表中有数十万份专利文件,因此手动分配财政年度不是一种选择。
最终目标是生成一个派生的基本统计表,如下所示(表 D):
Company | Financial Year | Count US Applications | Count US patents | Count EP Applications | ...
A | 2018 | 89 | 12 | 56 | ...
A | 2017 | 93 | 26 | 64 | ...
B | 2018 | 53 | 5 | 49 | ...
非常感谢。
这些表格按公司和日期范围相关,因此请加入这些表格。 这应该只是:
select *
from a
join b on a.company = b.company
and a.application_date between b.financial_year_start and b.financial_year_end;
这是演示(在 PostgreSQL 中),但您可以在 MariaDB 中应用相同的内容。
select
p.Company,
Publication_number,
Application_Date,
Financial_Year,
Document_Type,
Country_Code
from patent p
join financial_years fy
on p.Company = fy.Company
and Application_Date between
Financial_Year_Start and Financial_Year_End
对于你的最终结果,你可以用case
语句做这样的事情
select
Company,
Financial_Year,
sum(case when Country_Code = 'US' and Document_Type = 'patent' then 1 else 0 end) as 'Count US patents',
sum(case when Country_Code = 'US' and Document_Type = 'application' then 1 else 0 end) as 'Count US applications',
sum(case when Country_Code = 'EP' and Document_Type = 'patent' then 1 else 0 end) as 'Count EP patents',
sum(case when Country_Code = 'EP' and Document_Type = 'application' then 1 else 0 end) as 'Count RP applications'
from yourTable
group by
Company,
Financial_Year
order by
Financial_Year
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.