【问题标题】:PostgreSQL COUNT DISTINCT on one column while checking duplicates of another columnPostgreSQL COUNT DISTINCT 在一列上检查另一列的重复项
【发布时间】:2019-01-09 08:58:44
【问题描述】:

我有一个查询结果是这样一个表:

guardian_id | child_id | guardian_name | relation | child_name |
------------|----------|---------------|----------|------------|
    1       |   1      | John Doe      | father   | Doe Son    |
    2       |   1      | Jane Doe      | mother   | Doe Son    |
    3       |   2      | Peter Pan     | father   | Pan Dghter |
    4       |   2      | Pet Pan       | mother   | Pan Dghter |
    1       |   3      | John Doe      | father   | Doe Dghter |
    2       |   3      | Jane Doe      | mother   | Doe Dghter |

所以从这些结果中,我需要计算家庭。也就是说,不同的孩子有相同的监护人。从上面的结果来看,有 3 个孩子,但有 2 个家庭。我怎样才能做到这一点?

如果我这样做:

SELECT COUNT(DISTINCT child_id) as families FROM (
  //larger query
)a

我会得到 3,这是不正确的。 或者,我怎样才能合并一个检查DISTINCT Guardian_id 的WHERE 子句?还有其他方法吗?

另请注意,在某些情况下,孩子可能只有一名监护人。

【问题讨论】:

  • 你真的还在使用 Postgres 9.1 吗? [现在已经超过两年了)(postgresql.org/support/versioning)。您应该尽快计划升级。
  • 是的,系统严重依赖 postgres 9.1(使用相同 RDBMS (postgres 9.1) 的多个应用程序)- 至于升级,团队中其他更高级的成员对此有发言权

标签: postgresql count distinct postgresql-9.1


【解决方案1】:

要获得不同的家庭,您可以尝试以下方法。

select distinct array_agg(distinct guardian_id) 
from family
group by child_id;
上面的查询将返回唯一族的列表。 例如。
{1,2}
{3,4}
现在您可以在其上应用计数。

【讨论】:

    猜你喜欢
    • 2022-01-09
    • 2013-08-01
    • 2019-04-18
    • 1970-01-01
    • 2021-11-06
    • 1970-01-01
    • 1970-01-01
    • 2019-03-30
    • 1970-01-01
    相关资源
    最近更新 更多