首页 > 解决方案 > 如何从表中选择所有列并计数?

问题描述

我正在尝试选择表中的所有列top_teams_team以及获取该hash_value列的值的计数。此处的 sql 语句部分起作用,因为它返回两列,hash_value并且total. 我仍然希望它也给我表格的所有列。

select hash_value, count(hash_value) as total
from top_teams_team
group by hash_value

在下面的 sql 语句中,它给了我所有的列,但是显示了重复的 hash_value,这不是我想要的。我尝试输入distinct关键字,但它不能正常工作,或者我没有把它放在正确的位置。

select *
from top_teams_team
inner join (
    select hash_value, count(hash_value) as total
    from top_teams_team
    group by hash_value
) q
on q.hash_value = top_teams_team.hash_value

标签: sqlpostgresqlcountgreatest-n-per-groupwindow-functions

解决方案


我假设当您说:“但显示重复的 hash_value”时,您得到了重复的列

select q.hash_value, q.total, ttt.field1, ttt.field2, ttt.field3
from top_teams_team ttt
join (
    select hash_value, count(hash_value) as total
    from top_teams_team
    group by hash_value
) q
on q.hash_value = top_teams_team.hash_value

推荐阅读