Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/eclipse/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
获取SQL中只有1个类别的所有用户_Sql_Postgresql - Fatal编程技术网

获取SQL中只有1个类别的所有用户

获取SQL中只有1个类别的所有用户,sql,postgresql,Sql,Postgresql,我有这个表,U代表用户,C代表类别。我需要一种方法来查询用户有多少个类别,并将其限制为1。所以基本上,我需要得到所有只有一个类别的用户。如何使用SQL PostgreSQL实现这一点 我已经尝试寻找Stackoverflow的解决方案一段时间了,但没有成功 id U C 1 3 5 2 1 3 3 3 5 4 5 2 5 11 5 6 11 5 预期结果: 使用HAVING子句很容易: 您可以根据需要使用窗口功能 如果没有副本,则可以使用“不存

我有这个表,U代表用户,C代表类别。我需要一种方法来查询用户有多少个类别,并将其限制为1。所以基本上,我需要得到所有只有一个类别的用户。如何使用SQL PostgreSQL实现这一点

我已经尝试寻找Stackoverflow的解决方案一段时间了,但没有成功

id  U   C
1   3   5
2   1   3
3   3   5
4   5   2
5   11  5
6   11  5
预期结果:

使用HAVING子句很容易:

您可以根据需要使用窗口功能


如果没有副本,则可以使用“不存在”:

如果要重新分配序列号,请同时使用行号:


预期的结果是什么,为什么?嗨,马库斯,请同时添加到目前为止您已经尝试过的内容。现在添加预期的结果来说明。这不是很简单,因为它会抱怨id不在GROUPBY子句中;我已经更新了你的答案。啊,是的,对不起。我修正了它。@LaurenzAlbe谢谢,但是由于我的行数太多,在100万行之后,它会使整个GUI崩溃。但是不管你如何查询,行数都不会有什么不同,对吗?您可以添加限制来限制结果行的数量。谢谢!如何更改此项以处理重复项?@Marcus。您可以使用id,而不是希望保证一行,即使多行可能具有相同的u和c值。
id  U   C
1   1   3
2   5   2
SELECT max(id), u, max(c)
FROM atable
GROUP BY u HAVING count(c) = 1
SELECT DISTINCT * FROM(
SELECT a.*,count(c)over(partition by id) as cnt
FROM testtable a
) WHERE CNT=1
select t.*
from t
where not exists (select 1 from t t2 where t2.u = t.u and t2.c <> t.c);
select t.*
from t
where not exists (select 1 from t t2 where t2.u = t.u and t2.id <> t.id);
select row_number() over (order by id) as new_id, t.*
from t
where not exists (select 1 from t t2 where t2.u = t.u and t2.c <> t.c);