0

I am working on product data, part of which has the below structure (let's call it product_serials):

Table Structure

The table is a collection of product serial numbers. The snapped field determines whether a specific product has been purchased or not via it's serial number. Am trying to query the table to get a count of both all serials and also all unpurchased serials of the same product_id, using a single SQL query. So far using COUNT(ps1.id) AND COUNT(ps2.id) ... WHERE ps2.snapped = FALSE does not seem to work, it still counts the same values for both all serials and unpurchased serials, and even exaggerates the count, so am definitely doing something wrong.

What could I be missing?

My SQL query as requested:

SELECT pd.id AS product_id, pd.description, 
COUNT(pds.id) AS total, COUNT(pds2.id) AS available 
FROM products pd 
LEFT JOIN product_serials pds ON pds.product_id = pd.id 
LEFT JOIN product_serials pds2 ON pds2.product_id = pd.id 
WHERE pds2.snapped = FALSE
GROUP BY pd.id 
ORDER BY pd.date_added DESC
1
  • Please provide a complete query you tried Commented Jul 5, 2018 at 8:53

1 Answer 1

1

Here you join tables (even multiplying them) and then apply a WHERE condition to both.

I suggest something like the following:

SELECT product_id, count(serial), count(unpurchased)
  FROM (SELECT product_id, serial,
      CASE WHEN snapped THEN NULL ELSE 1 END AS unpurchased)
  GROUP BY product_id
Sign up to request clarification or add additional context in comments.

2 Comments

It will select 1 for a not purchased product and Null for a purchased one. Count on this column will give you the count of 1s (i.e. not purchased).
Yap, this is just like using a derived table, worked for me. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.