我正在尝试选择表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
答案 0 :(得分:0)
我假设当您说:“但是有重复的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
答案 1 :(得分:0)
尝试将COUNT
用作分析函数:
SELECT *, COUNT(*) OVER (PARTITION BY hash_value) total
FROM top_teams_team;
答案 2 :(得分:0)
将窗口函数与DISTINCT ON
结合使用可能会满足您的需求:
SELECT DISTINCT ON (hash_value)
*, COUNT(*) OVER (PARTITION BY hash_value) AS total_rows
FROM top_teams_team
-- ORDER BY hash_value, ???
;
DISTINCT ON
是在窗口函数之后 应用的,因此Postgres在选择每个组的第一行(包括该计数)之前首先对每个不同的hash_value
进行行计数。>
查询从每个组中选择一个任意行。如果需要特定的表达式,请相应地添加ORDER BY
个表达式。
这不是“ hash_value
列的值计数” ,而是每个不同的hash_value
行数/ strong>。我想那是你的意思。
详细说明:
根据未公开的信息,查询样式可能会(快得多)...