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

How can I remove duplicate data from joining data after group by?

I have 3 tables likes below erd

enter image description here

I’m trying to get max number of count product id by desc order count. Then I also add isFavorite depend on user favourites product in favourites table. My expected Json looks like

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

{
    "id": 2,
    "title": "30 % discount on pizza.",
    "price": 100,
    "count": 4,
    "isFavorite": false
},

I have tried below query

SELECT PRODUCTS.ID AS "Products__id",
    PRODUCTS.TITLE AS "Products__title",
    PRODUCTS.PRICE AS "Products__price",
    (COUNT(INVOICES.PRODUCT_ID)) AS "count",
    CASE
                    WHEN FAVORITES.USER_ID IS NULL THEN FALSE
                    ELSE TRUE
    END AS "isFavorite"
FROM PRODUCTS PRODUCTS
LEFT JOIN FAVORITES FAVORITES ON FAVORITES.PRODUCT_ID = PRODUCTS.ID
INNER JOIN INVOICES INVOICES ON PRODUCTS.ID = INVOICES.PRODUCT_ID
GROUP BY PRODUCTS.ID,
    FAVORITES.USER_ID
ORDER BY COUNT DESC
LIMIT 100

Problem is I’m getting duplicate values

enter image description here

How I will remove this duplicate ?

>Solution :

That will happen if more than one user marks the product as a favorite.

The quick answer is to use an aggregate function on the case statement and remove favorites.user_id from the grouping:

SELECT PRODUCTS.ID AS "Products__id",
       PRODUCTS.TITLE AS "Products__title",
       PRODUCTS.PRICE AS "Products__price",
       COUNT(INVOICES.PRODUCT_ID) AS "count",
       BOOL_OR(    
         CASE
           WHEN FAVORITES.USER_ID IS NULL THEN FALSE
           ELSE TRUE
         END
       ) AS "isFavorite"
  FROM PRODUCTS PRODUCTS
       LEFT JOIN FAVORITES FAVORITES 
         ON FAVORITES.PRODUCT_ID = PRODUCTS.ID
       JOIN INVOICES INVOICES 
         ON INVOICES.PRODUCT_ID = PRODUCTS.ID
 GROUP BY PRODUCTS.ID
 ORDER BY COUNT DESC
LIMIT 100
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