【问题标题】:How to select all columns and count from a table?如何从表中选择所有列并计数?
【发布时间】:2020-01-22 12:08:33
【问题描述】:

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

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

【问题讨论】:

  • 示例数据在这里会有所帮助。
  • 如果您希望“所有列”伴随一个聚合字段,您必须定义要从哪些聚合行中选择其他列。为了获得最佳查询,您还必须披露 Postgres 版本、表定义、行数以及每个 hash_value 预计有多少行?

标签: sql postgresql count greatest-n-per-group window-functions


【解决方案1】:

窗口函数与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 的行计数。我想这就是你的意思。

详细解释:

根据未公开的信息,可能会有(很多)更快的查询样式...

【讨论】:

  • 这成功了!太感谢了。我是 Postgres 的菜鸟,所以我整天都在试图弄清楚这一点。非常感谢您的帮助。
【解决方案2】:

我假设当您说:“但是显示重复的 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

【讨论】:

    【解决方案3】:

    尝试使用COUNT 作为解析函数:

    SELECT *, COUNT(*) OVER (PARTITION BY hash_value) total
    FROM top_teams_team;
    

    【讨论】:

      猜你喜欢
      • 2013-07-03
      • 2021-12-30
      • 1970-01-01
      • 2011-11-06
      • 2022-09-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多