I
I
Ivan_R22020-09-25 10:23:59
PostgreSQL
Ivan_R2, 2020-09-25 10:23:59

How to combine two queries into one grouping by condition in SQL?

Hello!
Please tell me how this can be done:
There is a request

SELECT Count(sales.id),  sale_group.code AS group
        FROM sales
        INNER JOIN sale_group
                    ON sales.group_id = sale_group.id
        GROUP BY sale_group.code
, which counts the number of orders for each group. How can I make it so that the result also displays groups for which there are no orders?

UPD:

Lazy, thanks a lot for the answer and for the infographic. Only I still had a condition there for filtering orders, I didn’t think that it would affect the result, I didn’t write it, I made a mistake. Doesn't work with him.
The complete request looks like this:
SELECT Count(sales.id), sale_group.code AS group
FROM sales
INNER JOIN sale_group
ON sales.group_id = sale_group.id
WHERE sales.path
LIKE '43/44/45/%' AND sales.id != 45
GROUP BY sale_group.code


After your answer I tried to do it like this:

SELECT Count(id FROM sales WHERE path
LIKE '43/44/45/%' AND id != 45), sale_group.code AS group
FROM sales
RIGHT JOIN sale_group
ON sales.group_id = sale_group.id
GROUP BY sale_group.code


But he thinks wrong. I apologize that I did not immediately write all the information, this is out of ignorance. Tell me, please, how to do it right now?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
L
Lazy @BojackHorseman, 2020-09-25
SQL

RIGHT JOIN sale_group ON sales.group_id = sale_group.id

5f6d9cd856202626798429.png

M
MaLuTkA_UA, 2020-09-25
@MaLuTkA_UA

SELECT Count(s.id), sg.code AS group
FROM sale_group sg
LEFT JOIN sales s ON s.group_id = sg.id AND s.path LIKE '43/44/45/%' AND s.id <> 45
GROUP BY sg.code

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question