count(distinct depositor.account_number)的使用是否会产生影响

问题描述 投票:0回答:2

给定数据库架构:[表的主键以粗体显示)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不会在此处添加任何值。

sql database
2个回答
1
投票

似乎depositor表存储了customer_nameaccount_number的独特组合,这意味着在计数中添加DISTINCT不应该有所作为。

但是如果表是一个事实表,它具有相同account_number的重复实例,你不会想要计算两次相同的帐号,在这种情况下,它会有所不同。

但在你的情况下,它应该没有区别,因为其他两个表似乎也包含各自字段的唯一组合。


0
投票

由于存款人表没有主键约束,因此可以复制名称 - 帐户配对。您的教科书可能没有讨论过复合键,因此这可能是一种捕捉该场景的方法。不幸的是,虽然获得三个账户资格是正确的,但额外的行仍然会抛弃平均计算。

© www.soinside.com 2019 - 2024. All rights reserved.