30

I have a table with with 2 unique linked table ids. I get the results I want with GROUP BY but when I count I only get the number of each group.

When I do:

SELECT COUNT(id) FROM my_table GROUP BY first_linked_table_id, second_linked_table_id

I get as results 1, 2, 3, 1 but I want 4 as a result.

I tried DISTINCT but I think that only works with one column

4
  • No, DISTINCT works with any number of columns, but it won't change much as DISTINCT is usually implemented by GROUP BY under the hood. Please include some sample data here. Commented Feb 21, 2017 at 8:49
  • @TimBiegeleisen DISTINCT only returns the unique values of one specific column, what I want is every row where the combination first_linked_table_id and second_linked_table_id is unique Commented Feb 21, 2017 at 9:06
  • No, you're wrong. You can use DISTINCT field1, field2, but in any case this is irrelevant to your question. Commented Feb 21, 2017 at 9:07
  • I know DISTINCT field1, field 2 is possible but it's not what I'm looking for. That returns 1, 1 and 2, 1 where I also want 1, 2 and 1, 3 Commented Feb 21, 2017 at 9:15

2 Answers 2

54

Your requirement is to get count of number of groups. So we need two operations-

  1. Group(inner query)
  2. Count(outer query)

Following query will do precisely that:

SELECT COUNT(*)
FROM
(
    SELECT COUNT(id) 
    FROM my_table 
    GROUP BY first_linked_table_id,
             second_linked_table_id
) t
Sign up to request clarification or add additional context in comments.

3 Comments

it returns the error: Every derived table must have its own alias
sorry, I tried using an enter submitting my comment when it wasnt ready. I edited it
Try This answers are low-value on StackOverflow because they do a poor job of educating/empowering the OP and thousands of future researchers about how your solution works and why it is a good solution. Please take a moment to explain your answer so that it is more valuable to readers and role models better posting behavior to new users.
6

If you want to count the rows, I think you're going to need a subquery. Something like this:

SELECT COUNT(*) FROM (
    SELECT COUNT(id) FROM my_table GROUP BY first_linked_table_id, second_linked_table_id
);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.