3

I have this 3 tables:

Users:
user_id|user_nick
   1   |    a
   2   |    b

Category:
cat_id|cat_type
   1  |    a
   2  |    b
   3  |    c
   4  |    d

Meta:
met_id|met_name|met_user|met_type
   10 |  bla   |    1   |    1
   11 | blabla |    2   |    2
   12 |  foo   |    1   |    3
   13 | blafoo |    2   |    4
   14 | foofoo |    1   |    4
   15 | foobla |    1   |    4

How can I return something like this ?

user_id|met_type|total
   1   |   1    |  1
   1   |   2    |  0
   1   |   3    |  1
   1   |   4    |  2

For just one user and not for all of them.

met_type is a foreign key from Category.

I've tried like this but no success :/

SELECT met_user, met_type, COUNT(*) FROM Meta GROUP BY met_user WHERE met_user = '1'

3
  • 1
    Yeah, I think GROUP BY met_user isn't what you want to do here. The distinct groups are met_type with 1, 2, 3, 4, so. Commented Jun 21, 2014 at 3:48
  • You should use group_concat function. Commented Jun 21, 2014 at 3:55
  • @VijayBarbhaya You should make an answer. :) Commented Jun 21, 2014 at 4:18

1 Answer 1

2

Query:

SELECT met_user, met_type, count(*)
FROM Meta
WHERE met_user='1'
  GROUP BY met_type;

To get empty groups, you can use generateSeries() here:

SELECT m.met_user, g.meta_type, count(m)
FROM generate_series(1, 4) AS g(meta_type)
  LEFT OUTER JOIN Meta AS m
    ON m.met_user='1'
    AND m.met_type=g.meta_type
GROUP BY g.meta_type, m.met_user
ORDER BY g.meta_type;

Check it out! I made an sql fiddle.

Sign up to request clarification or add additional context in comments.

4 Comments

Would you like empty met_type groups to show up too?
Thanks, I never thought about trying to group by met_type instead of met_user. Must the late hours heheh
Yes, that would be great if the empty ones showed up :)
@SnakeSheet Added - I also made an SQL Demo.

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.