I have rcently started working in SQL and need some help in query optimization.I am trying to achieve two measures "total_used" and "total_repair" in the final result set from each of the two tables "USAGE" and "Pair_Report" by making use of join but its making the performancy of query quite slow. Any suggestion/help on performance improvement wud be great. I have attached in the image the data example and sample data script is given at the bottom.
final query which i have written is this:
SELECT a.code, sum(a.total_used) as total_used, sum(b.total_pair) as total_pair FROM ( SELECT used_code AS code, b.sku as sku, COUNT(a.used_code) AS total_used FROM usage a LEFT JOIN pair_report b ON a.ma_number = b.ma_number and (a.ei = b.ei or a.ei = b.ei_out)
AND a.pair_date = b.pair_date WHERE a.pair_date >= '2019-10-01' and a.pair_date <= '2019-10-31' AND b.ma_number IS NOT NULL AND a.ma_number IS NOT NULL GROUP BY 1, 2 ) a
LEFT JOIN
( SELECT b.sku, COUNT(DISTINCT concat(b.ma_number, b.ei)) AS total_pair FROM usage a LEFT JOIN pair_report b ON a.ma_number = b.ma_number and (a.ei = b.ei or a.ei = b.ei_out) AND a.pair_date = b.pair_date WHERE a.pair_date >= '2019-10-01'and a.pair_date
<= '2019-10-31' AND b.ma_number IS NOT NULL AND a.ma_number IS NOT NULL GROUP BY 1 ) b
ON a.sku = b.sku group by 1
and here is data sample script:
CREATE TABLE #usage
(
Code VARCHAR(5),
Pair_Date DATETIME,
MA_NUMBER VARCHAR(5)
EI VARCHAR(5). Primary Key
)
CREATE TABLE #pair_report
(
SKU VARCHAR(5),
MA_NUMBER VARCHAR(5),
EI VARCHAR(5) Primary key,
Pair_Date DATETIME,
EI_OUT VARCHAR(5)
)
INSERT INTO #usage
(Code, Pair_Date, MA_NUMBER, EI)
VALUES
('A','20191112','1A','1A1'),
('A','20191112','1A','1A2'),
('A','20191112','1B','1B1'),
('B','20191112','1B','1BE')
INSERT INTO #PAIR_REPORT
(SKU, MA_NUMBER, EI, Pair_Date, EI_OUT)
VALUES
('FA','1A','1A1','20191112','1A1'),
('FA1','1A','1C1','20191112','1A2'),
('FA3','1B','1BE','20191112','1BE')
Any help on this would be great. I am kind of stuck into this issue from long.