Table1# t1
id | name | include
-------------------
1 | foo | true
2 | bar | true
3 | bum | false
Table2# t2
id | some | table_1_id
-------------------------
1 | 42 | 1
2 | 43 | 1
3 | 42 | 2
4 | 44 | 1
5 | 44 | 3
Desired output:
name | count(some)
------------------
foo | 3
bar | 1
SOLUTION:
SELECT a.name, COUNT(r.some) FROM t1 a JOIN t2 r on a.id=r.table_1_id WHERE a.include = 'true' GROUP BY a.name
Columns you want to use in an aggregate function like sum() or count() must be left out of the group by clause. Only put the columns in there you want to be unique outputted.
id | name | include
-------------------
1 | foo | true
2 | bar | true
3 | bum | false
Table2# t2
id | some | table_1_id
-------------------------
1 | 42 | 1
2 | 43 | 1
3 | 42 | 2
4 | 44 | 1
5 | 44 | 3
Desired output:
name | count(some)
------------------
foo | 3
bar | 1
SOLUTION:
SELECT a.name, COUNT(r.some) FROM t1 a JOIN t2 r on a.id=r.table_1_id WHERE a.include = 'true' GROUP BY a.name
Columns you want to use in an aggregate function like sum() or count() must be left out of the group by clause. Only put the columns in there you want to be unique outputted.
0 comments:
Post a Comment