Question

I have the following schema http://sqlfiddle.com/#!2/1241f9/9

The first query show the entire collection of data i collect from the tables.

What I am trying to do is create a test to check the display of a product on the website however i want it to be dynamic because when we run a test a product may no longer be available

to do this I want to find out which parent_id have more than 3 child_id's, have at least one child_id where qty > 0, has at least one child_id where qty = 0 and wh_soh > 0 and has at least one child_id where both qty and wh_soh = 0.

these 3 conditions indicate 3 states a child_id can be in

  • in stock (qty > 0)
  • out of stock but can be resupplied from warehouse (qty = 0 and wh_soh > 0)
  • completely out of stock (qty and wh_soh = 0)

I can filter the results so that i get all the parent_id's that have 3 or more child_id's (second query), the next step is to do something like COUNT(WHERE qty = 0 AND wh_soh = 0) but when I google , I keep finding results for counting unique values in a group.

So how can I do a conditional count in my query ie. COUNT(WHERE qty = 0 AND wh_soh = 0)

Was it helpful?

Solution

try this query, you can count the conditions by using SUM(condition) like below

SELECT p.parent_id,
       COUNT(*) as children,
       SUM(c.qty > 0) as in_stock,
       SUM(c.qty = 0 AND c.wh_soh > 0) as warehouse,
       SUM(c.qty = 0 AND c.wh_soh = 0) as out_of_stock
FROM test_parent p 
INNER JOIN test_relation r USING (parent_id)
INNER JOIN test_child c USING (child_id)
GROUP BY p.parent_id
HAVING children > 3
   AND in_stock > 0
   AND warehouse > 0
   AND out_of_stock > 0

sqlFiddle

OTHER TIPS

Try this:

SELECT a.parent_id, a.url 
FROM (SELECT tr.parent_id, tp.url, tr.child_id, 
            (CASE WHEN tc.qty > 0 THEN 1 WHEN tc.qty = 0 AND tc.wh_soh > 0 THEN 2 WHEN tc.qty = 0 AND tc.wh_soh = 0 THEN 3 END) AS test 
      FROM test_relation AS tr
      INNER JOIN test_parent AS tp ON tr.parent_id = tp.parent_id
      INNER JOIN test_child AS tc ON tc.child_id = tr.child_id
    ) AS a
GROUP BY a.parent_id HAVING COUNT(DISTINCT child_id) >=3 AND COUNT(DISTINCT test) >= 3;

Check this link SQL FIDDLE DEMO

OUTPUT

| PARENT_ID |   URL |
|-----------|-------|
|         5 | url_e |
|        11 | url_k |
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top