给定数据库架构:[表的主键以粗体显示)account(account_no,branch_name,balance)depositor(customer_name,account_number){此处未说明密钥} customer(customer_name,customer_street,customer_city)
编写SQL查询所需的问题 - 查找居住在哈里森并拥有至少3个帐户的每个客户的平均余额。
我写了以下SQL查询:
select depositor.customer_name,avg(balance)
from depositor,account,customer
where depositor.account_number=account.account_number and
depositor.customer_name=customer.customer_name and
customer_city='Harrison'
group by depositor.customer_name
having count(depositor.account_number) >=3
我的教科书提到查询为:
select depositor.customer_name,avg(balance)
from depositor,account,customer
where depositor.account_number=account.account_number and
depositor.customer_name=customer.customer_name and
customer_city='Harrison'
group by depositor.customer_name
having count( distinct depositor.account_number) >=3
在这里放置不同会导致结果的变化吗?根据我的分析,结果关系(depositoraccountcustomer)的交叉产品将候选键作为customer_name account_number,因此distinct不会在此处添加任何值。
似乎depositor
表存储了customer_name
和account_number
的独特组合,这意味着在计数中添加DISTINCT不应该有所作为。
但是如果表是一个事实表,它具有相同account_number
的重复实例,你不会想要计算两次相同的帐号,在这种情况下,它会有所不同。
但在你的情况下,它应该没有区别,因为其他两个表似乎也包含各自字段的唯一组合。
由于存款人表没有主键约束,因此可以复制名称 - 帐户配对。您的教科书可能没有讨论过复合键,因此这可能是一种捕捉该场景的方法。不幸的是,虽然获得三个账户资格是正确的,但额外的行仍然会抛弃平均计算。