gpt4 book ai didi

sql - 如何在 having 子句中有 'distinct'

转载 作者:行者123 更新时间:2023-12-01 22:30:56 25 4
gpt4 key购买 nike

编辑:这是一个示例关系!我需要它来处理更大的关系,所以没有解决方法!

所以我得到了一个简单的任务,起初我没有看到可能有什么问题,现在我只是不明白为什么它不起作用。

假设我有一张人和他们的 friend 的表格,我想选择那些有 2 个或更多 friend 的人。

------------------------------
|person | friend | relation |
|-----------------------------
|ana | jon | friend |
|ana | jon | lover |
|ana | phillip| friend |
|ana | kiki | friend |
|mary | jannet | friend |
|mary | jannet | lover |
|peter | july | friend |

我想做一个

 SELECT person FROM people GROUP BY person HAVING count(distinct friend) > 1;

得到

-------
| ana |
-------

但是在 HAVING 子句中使用 'distinct' 时出现语法错误。我知道“distinct”是投影子句的一部分,但是如何让“count”只计算不同的条目而不需要额外的子查询或其他东西?

编辑:我能想到的最好的是:

SELECT tmp.person FROM (SELECT person, count(distinct friend) 
AS numfriends FROM people GROUP BY person) AS tmp
WHERE tmp.numfriends > 1;

最佳答案

来自文档

http://www-01.ibm.com/support/knowledgecenter/SSGU8G_12.1.0/com.ibm.sqls.doc/ids_sqs_0162.htm

The condition in the HAVING clause cannot include a DISTINCT or UNIQUE aggregate expression.

解决方法是在选择中设置不同的计数

SELECT 
person,
count(distinct friend) as f_count
FROM people
GROUP BY person
HAVING f_count > 1;

更新:

查看文档,发现事实

The HAVING clause is evaluated before the SELECT - so the server doesn't yet know about that alias.

所以为了实现目标可以这样做

select
person,
f_count
from(
SELECT
person,
count(distinct friend) as f_count
FROM people
GROUP BY person
)x
where f_count > 1

关于sql - 如何在 having 子句中有 'distinct',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29555685/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com