计数不起作用

时间:2018-08-24 09:11:26

标签: sql postgresql

不确定今天早上我做了什么,但我必须非常努力地击打头

这是我的查询

select c.id as cid,c.studentid as cstudentid              
from certification c
group by c.id,c.studentid
order by c.studentid

我的结果是这个

 cid studentid
 35267  6400
 5332   6401
 35271  6402
144024 6402
252727 6402
434317 6402
529734 6405
...

我想要被废除两次以上的学生证,例如6402

我尝试了像这样的基本查询

select c.id as cid,c.studentid as cstudentid              
from certification c
group by c.id,c.studentid
having count(c.studentid) > 2
order by c.studentid

输出为空/无/无表...

系统:Postgres 9.3

我在做什么错了?

2 个答案:

答案 0 :(得分:2)

您的查询不符合您的期望。它返回所有行,每行计数为1。因为您已经将两个列都分组了。另外,它找不到要汇总的相关行。因此,您可以更改查询以将其按一个列(c.studentId)分组,然后汇总到另一列(c.id)。可能类似于以下代码:

select count(c.id), c.studentid as cstudentid              
from certification c
group by c.studentid
having count(c.id) > 2
order by c.studentid

如果您需要重复的c.id,则应编写CTE查询。 this post的第二个答案将为您提供帮助。

答案 1 :(得分:1)

尝试以下操作:但是,您应指定输出: 从您的表中按分组删除as的cid,看来cid是唯一的

select c.studentid as cstudentid              
from certification c
group by c.studentid
having count(c.studentid) > 2
order by c.studentid