1

I use Postgresql. I have a & b table like this

a_table
+--------+---------------+
|   id   |   free_value  |
+--------+---------------+
|   1    |      3        |
|   2    |      2        |
|   3    |      1        |
|   4    |      3        |
|   5    |      2        |
|   6    |      8        |
|   7    |      4        |
+--------+---------------+

b_table
+--------+---------------+
|   id   |   a_table_id  |
+--------+---------------+
|   1    |      2        |
|   2    |      2        |
|   3    |      6        |
|   4    |      5        |
|   5    |      3        |
|   6    |      3        |
+--------+---------------+

Can I write query for count free_value on b_table and desc to count like this ?

count_free_value_table
+----------------+-----------+
|   free_value   |   count   |
+----------------+-----------+
|       2        |     3     |
|       1        |     2     |
|       8        |     1     |
|       3        |     0     |
|       4        |     0     |
+----------------+-----------+

I try with SELECT free_value, count(free_value) from a_table LEFT JOIN b_table ON a_table.id = b_table.a_table_id But It is not work.

Thank you for any help. I am be silly for this.

1
  • 1
    SELECT free_value, count(*) from a_table LEFT JOIN b_table ON a_table.id = b_table.a_table_id group by free_value Commented Aug 2, 2016 at 22:29

3 Answers 3

1

Try COUNT(b_table.id) instead; COUNT counts all non-null values encountered, which is why (I am guessing) you were getting 1 for the unmatched free_values; because the unmatched values still have their own values in their rows.

Edit: Also, are's comment and Alim's answer are also correct in that you need to group by free_value. Otherwise, you'll get total rows of the JOIN, and an effectively randomly chosen free_value.

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

Comments

1

try

SELECT free_value, count(free_value)
from a_table LEFT JOIN b_table ON a_table.id = b_table.a_table_id 
group by free_value

2 Comments

counting free_value will result in 1's for values with no references.
I change count(free_value) to count(b_table.id) and it work right thank for @Uueerdo too. Thank you for help.
0
SELECT free_value, count( b_table.id ) count
FROM a_table
LEFT JOIN b_table ON a_table.id = b_table.a_table_id
GROUP BY free_value
ORDER BY count DESC

try this query.

Comments

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.