1

So this statement started off without the join, it would simply lookup the product tables and group results by item_code.

SELECT a.item_code,
       a.price,
       b.v_no
FROM product a
JOIN variation b ON a.item_code = b.item_code
WHERE a.price>=2
GROUP BY a.item_code

Now that I have added the join I want to group by v_no but ONLY if data v_no exists. This is because not every item from the product table has a corresponding entry in the variation table. So group by item_code for 'normal' products, but group by v_no THEN item_code if a v_no exists.

The below does not work:

SELECT a.item_code,
       a.price,
       b.v_no
FROM product a
JOIN variation b ON a.item_code = b.item_code
WHERE a.price>=2
GROUP BY b.v_no,
         a.item_code

The item_code grouping remains but the v_no grouping is ignored.

2

1 Answer 1

1
  • In order to consider all the product(s) (with/without variations), you will need to change to LEFT JOIN.
  • For conditional Group By, you can use Coalesce() function; it will consider the first non-null value for Grouping upon.

Try the following:

SELECT a.item_code,
       a.price,
       b.v_no
FROM   product a
       LEFT JOIN variation b
         ON a.item_code = b.item_code
WHERE  a.price >= 2
GROUP  BY COALESCE(b.v_no, a.item_code)
Sign up to request clarification or add additional context in comments.

1 Comment

@Guesser Happy to help. 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.