以下是数据库的架构:http://i.stack.imgur.com/omX60.png
问题是:有多少人至少有五个元素?
我有这个,请告诉我它是多么错误并修复它。
select count(personId)
from serialNumber_tbl natural join entitlement_tbl
group by personId
having sum(entitlementID) > 5
谢谢。
答案 0 :(得分:4)
至少为5的条件为>= 5
,而不是> 5
您需要计算权利表中的不同ID,而不是人
这给了你这些人,接下来你需要对它进行子查询以找到人数。
select count(personId)
FROM
(
select personId
from serialNumber_tbl natural join entitlement_tbl
group by personId
having count(distinct entitlement_id) >= 5
) X
答案 1 :(得分:1)
您的要求并不完全清楚。您是否要求拥有超过五个权利行的人数是否存在于多个序列号中?如果是这样,您可以执行以下操作:
Select Count(*) As CountOfPeople
From Person_tbl As P
Where Exists (
Select 1
From serialNumbers As S1
Join entitlement_tbl As E1
On E1.serialNumberId = S.serialNumberId
Where S1.personId = P.personId
Having Count(*) >= 5
)
或者您是否要求查找具有超过五种权利的serialNumber的人数?如果是这种情况,那么您可以执行以下操作:
Select Count(*) As CountOfPeople
From Person_tbl As P
Where Exists (
Select 1
From serialNumbers As S1
Join entitlement_tbl As E1
On E1.serialNumberId = S.serialNumberId
Where S1.personId = P.personId
Having Count( Distinct S1.serialNumberId ) >= 5
)