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

标签 sql informix

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

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

假设我有一张人和他们的 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/

相关文章:

c# - 在 Controller 操作中执行 SQL 查询

sql - JOIN 两个 SELECT 语句结果

python - 为什么 Python informixdb 包抛出错误!

database - Informix-577 : A constraint of the same type already exists on the column set

sql - 将转换后的格式更改为 ISO 日期 - SQL Server

sql - 这个 MySQL 数据库可以改进吗?或者它是好的吗?

SQL Informix 高级查询

sql - 如何只删除多余的数据?

sql - 如何从日期间隔中选择项目,无论年份如何 — Informix DB

sql - 一个数据库服务器一次可以有多少个打开的连接?