我一直在努力处理多重计数声明。 我的表是这样构建的;
person1, person2, relation
peter ann coworkers
我需要计算彼得在恋人之下有多少关系。等等
我想出了这个;
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
;
但我似乎无法让它发挥作用。
答案 0 :(得分:1)
select relation, count(*) as RelationCount
from rel
where person1='peter'
group by relation
答案 1 :(得分:1)
您的原始查询似乎需要一个透视结果。如果是这种情况,你需要类似的东西。
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
答案 2 :(得分:0)
假设
Peter, Ann, Coworker
还会有相应的条目:
Ann, Peter, Coworker
然后你可以这样做:
SELECT Person1, Relation, COUNT(1)
FROM Rel
GROUP BY Person1, Relation
否则,你可以这样做:
SELECT Person1, Relation, COUNT(1)
FROM Rel
GROUP BY Person1, Relation
UNION
SELECT Person2, Relation, COUNT(1)
FROM Rel
GROUP BY Person2, Relation