Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Query without full data

I have this query

SELECT
  U.Country,
  U.Product,
  Week,
  SUM(
    CASE WHEN Year = 2022
    THEN SoldUnits ELSE 0 END
  ) AS TotalSoldUnits
FROM Uploads U
INNER JOIN MaxWeek_Product T1
ON T1.Product = U.Product
  AND MaxWeek = Week
where U.country = 'GT'
GROUP BY U.Country, U.Product
ORDER BY U.Country;

It returns me something like this:

Country Product Week TotalSoldUnits
GT ABC003 7 245
GT ABC403 8 255
GT ABC073 7 145
GT ABCb03 10 240

The problem is that It has to return 500 rows and actually returns 480 rows.
I found that the problems is in AND MaxWeek = Week because some Products has Week = 0 in the table MaxWeek_Product but in the Uploads table, none of the Products have Week = 0. And those Products get lost in the INNER JOIN.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I tried using LEFT JOIN or RIGHT JOIN but still, it doesn’t work.

What can I do to retrieve those missing Products with TotalSoldUnits = 0.

Uploads table:

Country Product Week SoldUnits Year
GT ABC003 7 245 2022
GT ABC403 8 255 2022
GT ABC073 7 145 2022
GT ABCb03 10 240 2022
GT OBCb03 16 128 2021

MaxWeek_Product table:

Country Product MaxWeek
GT ABC003 7
GT ABC403 8
GT ABC073 7
GT ABCb03 10
GT ACb037 0

>Solution :

The main issue here is the WHERE statement, because it activates after the JOIN operations have taken effect, hence removing the rows that the LEFT/RIGHT JOIN could have saved (with NULL values).

Here is how it becomes after the changes:

SELECT
  T1.Country,
  T1.Product,
  T1.MaxWeek,
  SUM(CASE WHEN Year = 2022
           THEN SoldUnits 
           ELSE 0 
      END)                      AS TotalSoldUnits
FROM      MaxWeek_Product T1
LEFT JOIN Uploads U
       ON T1.Product = U.Product
      AND T1.MaxWeek = U.Week
      AND T1.country = 'GT'
GROUP BY T1.Country, 
         T1.Product, 
         T1.MaxWeek
ORDER BY T1.Country;

Try it at the SQL fiddle here.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading