I
I
Ivan_R22020-09-23 18:58:42
PostgreSQL
Ivan_R2, 2020-09-23 18:58:42

How to do a grouping with a count in SQL instead of outputting each row?

Hello!
I have a query that filters id in a table by a condition and outputs 2 columns - id and related record name from another table. The results are displayed like this:
5f6b6fb944207123292502.png
In other words, I need to count how many filtered records are in each group.
The request itself:

SELECT contacts.id, contact_group.name AS group
FROM contacts
INNER JOIN contact_group
            ON contacts.group_id = contact_group.id
WHERE contacts.path
        LIKE '43/44/45/%'
        AND contacts.id != 45

Answer the question

In order to leave comments, you need to log in

2 answer(s)
L
Lazy @BojackHorseman, 2020-09-23
@Ivan_R2

count, group by

V
Vitaly Voloboev, 2020-09-25
@VitaliiVV

the number of rows to be counted must be wrapped in the aggregate function COUNT,
and at the end of the query, after the conditions, grouped by columns WITHOUT aggregate functions.
You should get something like this -
SELECT COUNT(contacts.id) AS Id_Qty, contact_group.name AS group
FROM contacts
INNER JOIN contact_group
ON contacts.group_id = contact_group.id
WHERE contacts.path
LIKE '43/44/45/%'
AND contacts.id != 45
GROUP BY contact_group.name
code can be shortened by using aliases for table names,
for example SELECT c.id FROM contacts AS c (when working with multiple tables)
(in MS SQL Server, you can also omit AS - just write the column name separated by a space,
and 'INNER', there is a join without specifying the default type - just the inner)
ps and I also doubt the output order, I think if you need the number of IDs for groups , it is more logical to display them in the form - group1 - 10 pieces, group2 - 5

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question