Mysql: 我怎样才能连接两个表并找到每家公司最近一年的收入
Mysql: How can i join two tables and find the revenue of each company for latest year
这是两个有数据的表,如何连接这两个表并找到每个表的收入
公司最新可用年份。 如何编写 SQL 查询以获得预期结果?
Table ‘Companies’:
Id | companyCode| companyName
1 | comp1 | Tata Motors
2 | comp2 | Reliance
3 | comp3 | Infosys
4 | comp4 | HDFCBANK
Table ‘FinancialDatas’
Id | companyCode| year | revenue
12 | comp1 | 2019 | 12500
13 | comp1 | 2020 | 13250
14 | comp2 | 2018 | 45000
15 | comp2 | 2019 | 55000
16 | comp3 | 2019 | 9500
17 | comp3 | 2020 | 7500
18 | comp4 | 2017 | 11000
19 | comp4 | 2018 | 13500
Extexted OutPut Below:
companyName | year | revenue
Tata Motors |2020 |13250
Reliance |2019 |55000
Infosys |2020 |7500
HDFCBANK |2018 |13500
您可以使用row_number()
select * from
(
select companyName,year,revenue,row_number() over(partition by companyName order by year desc) as rn
from companies c join FinancialDatas f on c.companycode=f.companycode
)A where rn=1
这是两个有数据的表,如何连接这两个表并找到每个表的收入 公司最新可用年份。 如何编写 SQL 查询以获得预期结果?
Table ‘Companies’:
Id | companyCode| companyName
1 | comp1 | Tata Motors
2 | comp2 | Reliance
3 | comp3 | Infosys
4 | comp4 | HDFCBANK
Table ‘FinancialDatas’
Id | companyCode| year | revenue
12 | comp1 | 2019 | 12500
13 | comp1 | 2020 | 13250
14 | comp2 | 2018 | 45000
15 | comp2 | 2019 | 55000
16 | comp3 | 2019 | 9500
17 | comp3 | 2020 | 7500
18 | comp4 | 2017 | 11000
19 | comp4 | 2018 | 13500
Extexted OutPut Below:
companyName | year | revenue
Tata Motors |2020 |13250
Reliance |2019 |55000
Infosys |2020 |7500
HDFCBANK |2018 |13500
您可以使用row_number()
select * from
(
select companyName,year,revenue,row_number() over(partition by companyName order by year desc) as rn
from companies c join FinancialDatas f on c.companycode=f.companycode
)A where rn=1