1

I've been struggling with a multiple count statement. my table is build like this;

person1, person2, relation
peter     ann      coworkers

I need to count how many relations peter has under coworker, under lovers . etc etc

I've come up with this;

select(
select count(*)
from rel
where person1 = 'peter' and relation = 'coworker'
)as PetersFriends,(
select count(*)
from rel
where person1 = 'peter' and relation = 'lovers'
)
as PetersLovers
;

but I can't seem to get it to work.

3
  • Can you please try to elaborate more and use proper formatting. I'm afraid, that I don't understand your question. Also: Which DBMS do you use? Commented Mar 7, 2011 at 10:37
  • 1
    Are you 'peter'? What if you fall in love with a coworker? :) Commented Mar 7, 2011 at 10:38
  • Sounds like homework to me. Is it? If so, please mark it as such. Commented Mar 7, 2011 at 10:40

3 Answers 3

1
select relation, count(*) as RelationCount
from rel
where person1='peter'
group by relation
Sign up to request clarification or add additional context in comments.

2 Comments

I need to know how many of each relations peter, ann and wendy has
That's not what your question said. Perhaps you can elaborate from what I've provided above?
1

Your original query seems to want a pivoted result. If this is the case you would need something like.

select person1,
       COUNT(case when relation = 'coworker' then 1 end) AS Friends,
       COUNT(case when relation = 'lovers' then 1 end) AS Lovers
from rel
where person1 IN ('peter','ann','wendy')
GROUP BY person1

1 Comment

@user493417 - You need to give more details than that.
0

Assuming that

Peter, Ann, Coworker

Will also have a corresponding entry:

Ann, Peter, Coworker

Then you can simply do this:

SELECT Person1, Relation, COUNT(1)
FROM Rel
GROUP BY Person1, Relation

Otherwise, you can do this:

SELECT Person1, Relation, COUNT(1)
FROM Rel
GROUP BY Person1, Relation
UNION 
SELECT Person2, Relation, COUNT(1)
FROM Rel
GROUP BY Person2, Relation

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.