【问题标题】:table of the number of occurrences of numbers in the column postgresqlpostgresql 列中数字出现次数的表
【发布时间】:2018-10-03 20:07:17
【问题描述】:

我有一张桌子:

我的选择:

select  regexp_split_to_table(t3."Id"::character varying,'') as s
from (select t1."Id" from table1 t1
union all
select t2."Id"from table2 t2) t3
order by s

或者我也可以用这个得到一个字符串'22173345566179111134546175622323811':

select  string_agg(t3."Id"::character varying,'') as s
from (select t1."Id" from table1 t1
union all
select t2."Id"from table2 t2) t3

我需要得到一个包含 number|count 数据的表格,我的意思是任何数字都可以在选择中获取重复次数,例如:

1 | 9

2 | 5

3 | 5

等等..

PostgreSQL 数据库管理系统

【问题讨论】:

    标签: sql postgresql select count


    【解决方案1】:

    这是你想要的吗?

    select id, count(*)
    from (select t1."Id" from table1 t1
          union all
          select t2."Id" from table2 t2
         ) t3
    group by id
    order by id;
    

    【讨论】:

      【解决方案2】:

      如果我的理解正确,您需要一个包含所有数字的列表,这些数字存在于两个表的一组 ID 中,以及每个数字的计数,它在所有这些 ID 中出现的频率。如果是这样,您只需要GROUP BY 一个数字并使用count()

      SELECT s.d,
             count(*) count
             FROM (SELECT t1."Id"
                          FROM table1 t1
                   UNION ALL
                   SELECT t2."Id"
                          FROM table2 t2) t3
                  CROSS JOIN LATERAL regexp_split_to_table(t3."Id"::character varying, '') s(d)
             GROUP BY s.d
             ORDER BY s.d;
      

      【讨论】:

      • 绝对正确,但是......我不明白,你为什么使用 s(d) - 那是什么?功能?我看到“分组依据”和“排序依据” - s.d.溺爱。有点复杂……
      • @NikMatue:这不是函数,它是一个别名,将s 定义为regexp_split_to_table() 的“结果表”的别名,并将d 定义为该结果第一列的别名。
      • 有没有关于这个别名的文档?
      【解决方案3】:

      最简单的方法

      select regexp_split_to_table(t3."Id"::character varying,'') s,  count(*) count
      from (select t1."Id" from table1 t1 union all select t2."Id"from table2 t2) t3
      group by s
      

      【讨论】:

        猜你喜欢
        • 2023-01-20
        • 2021-05-30
        • 1970-01-01
        • 2020-03-27
        • 2011-06-14
        • 2022-11-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多