我有一个查询,请为我提供优化查询的可能方法。我使用了两个CTE,然后应用到JOIN。第一个CTE提供了2018年的数据,第二个CTE提供了2019年的数据。两个年度的两个联接数据都在我申请的国家/地区加入。
查询
with cte as
(
select aa.Country_Name, SUM(MQTY) Qty
from(
select *
from ExportData
where YEAR in ('0119','0219','0319') and
FINANCIAL_YEAR='2018-19'
union
select *
from ExportData
where YEAR not in ('0120','0220','0320') and
FINANCIAL_YEAR='2019-20'
)ab
inner join countrymaster aa on COD=Country_Code
where DCODE in ('0502','0503','0504','0505','0506','0507','0508')
group by aa.Country_Name
)
,cte1 as
(
select aa.Country_Name, SUM(MQTY) Qty
from (
select *
from ExportData
where YEAR in ('0118','0218','0318') and
FINANCIAL_YEAR='2017-18'
union
select *
from ExportData
where YEAR not in ('0119','0219','0319') and
FINANCIAL_YEAR='2018-19'
)ab
inner join countrymaster aa on COD=Country_Code
where DCODE in ('0502','0503','0504','0505','0506','0507','0508')
group by DGCTRCOD,aa.Country_Name
)
select cte.Country_Name, cte1.Qty 'Qty 2018', cte.Qty 'QTY 2019' from cte
inner join cte1 on cte.Country_Name = cte1.Country_Name
您可以先避开(选择*),然后仅选择所需的列。