1

This is supposed to be a very simple problem, but somehow I am completely stuck... This is a simplified example to show the problem:

Table:
int     ID (primary key)
varchar Child
varchar Toy

Running

SELECT Child, Toy FROM TestTable

gives me:

Child    Toy
------------------------
A        T_A
B        T_B
A        T_C
C        T_D  
A        T_E
B        T_F

I need a query that returns me the Child/Toy entries only for children that have more then 2 toys - only one in this example. So the output should look like this:

Child    Toy
------------------------
A        T_A
A        T_C
A        T_E
1
  • For clarity, it would be useful if you could specify which flavour of SQL you are programming for Commented Jan 13, 2012 at 16:08

4 Answers 4

8

This finds children with more than two toys:

select Child
from TestTable
group by Child
having count(*) > 2

Then you can do this to get all columns back that you want:

select Child, Toy
from TestTable 
where Child in (
    select Child
    from TestTable
    group by Child
    having count(*) > 2
)
Sign up to request clarification or add additional context in comments.

3 Comments

Actually it finds children with more than one ROW. OP should be advised this will count duplicate toys as well.
+1 : And, I'd JOIN rather than using IN. But it's the same concept :)
Thank you for your really fast response, but this does not give me the desired output. I need 'Child' and 'Toy' in the output, so SELECT Child, Toy ....
3
SELECT Child, Toy
FROM TestTable
WHERE Child IN
(
    SELECT Child
    FROM TestTable
    GROUP BY Child
    HAVING COUNT(*) > 2
)

Comments

1
SELECT Child, Toy
FROM TestTable
WHERE child IN(
   SELECT Child FROM TestTable group by Child having count(*)>2
)

Comments

0

This query should work

SELECT
    Child,
    Toy
FROM TestTable t
WHERE
    t.Child IN 
    (
        SELECT Child
        FROM TestTable  
        GROUP BY Child
        HAVING COUNT(*) > 2         
    )   

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.