【问题标题】:Help construct a query given a schema帮助构建给定模式的查询
【发布时间】:2011-08-01 04:55:55
【问题描述】:

这是数据库的架构:http://i.stack.imgur.com/omX60.png

问题是:有多少人拥有至少五项权利?

我遇到了这个问题,请告诉我它有什么问题并修复它。

select count(personId)
from serialNumber_tbl natural join entitlement_tbl
group by personId
having sum(entitlementID) > 5

谢谢。

【问题讨论】:

    标签: sql tsql schema


    【解决方案1】:

    至少 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
    

    【讨论】:

    • 谢谢,这正是我需要的!
    【解决方案2】:

    您的要求并不完全清楚。您是否要求计算具有超过五个权利行的人是否存在于多个序列号上?如果是这样,您可以执行以下操作:

    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
                    )
    

    或者您是要查找拥有超过五个权利的序列号的人数?如果是这种情况,那么您可以执行以下操作:

    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
                    )
    

    【讨论】:

      猜你喜欢
      • 2011-08-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多