开发者

Help construct a query given a schema

开发者 https://www.devze.com 2023-02-23 02:55 出处:网络
Here is the schema for the database: http://i.stack.imgur.com/omX60.png Question is: How many people have at least five еntitlements?

Here is the schema for the database: http://i.stack.imgur.com/omX60.png

Question is: How many people have at least five еntitlements?

I've got this, please tell me how wrong it is and fix it.

select count(personId)
from serialNumber_tbl natural join entitlement_tbl
group by personId
having sum(entitlemen开发者_StackOverflowtID) > 5

Thank you.


The condition for at least 5 is >= 5, not > 5
You need to count the distinct ids in the entitlement table, not person
This gives you the persons, next you need to subquery it to find the count of persons.

select count(personId)
FROM
(
select personId
from serialNumber_tbl natural join entitlement_tbl
group by personId
having count(distinct entitlement_id) >= 5
) X


Your request isn't exactly clear. Are you asking for the count of people with more than five entitlement rows whether they exist on multiple serial numbers or not? If so, you could do something like:

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
                )

Or is it that you are asking to find the number of people that have a serialNumber with more than five entitlements? If that is the case, then you could do something like:

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
                )
0

精彩评论

暂无评论...
验证码 换一张
取 消