5

I have two tables

A and B

 A                          B
-----------------         -----------------
a_pk (int)                b_pk (int)
a_name(varchar)           a_pk (int)
                          b_name (varchar) 

I could write a query

SELECT a.a_name, b.b_name
FROM  a LEFT OUTER JOIN b ON a.a_pk = b.a_pk

and this would return me a non distinct list of everything in table a and its table b joined data. Duplicates would display for column a where different b records shared a common a_pk column value.

But what I want to do is get a full list of values from table A column a_name and ADD a column that is a COUNT of the joined values of table B.

So if a_pk = 1 and a_name = test and in table b there are 5 records that have a a_pk value of 1 my result set would be

a_name        b_count
------        -------
test           5

3 Answers 3

11

The query should like this :

SELECT 
    a.a_name, 
    (
        SELECT Count(b.b_pk) 
        FROM b 
        Where b.a_pk = a.a_pk
    ) as b_count 
FROM  a
Sign up to request clarification or add additional context in comments.

Comments

4
SELECT a_name, COUNT(*) as 'b_count'
FROM 
    A a
    JOIN B b
    ON a.a_pk = b.a_pk
GROUP BY a_name

Comments

0
SELECT
    a.name,
    (
        SELECT COUNT(1)
        FROM B b
        WHERE b.a_pk = a.a_pk
    )
FROM A a

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.