【问题标题】:PostgreSQL merge COUNT and GROUP BY resultPostgreSQL 合并 COUNT 和 GROUP BY 结果
【发布时间】:2018-05-23 08:37:07
【问题描述】:
select type, created_at::date , count(type)
from txns
group by created_at::date, type
order by created_at::date;

上面的 SQL 查询给出以下输出:

  type   | created_at | count 
---------+------------+-------
 full    | 2017-05-20 |     2
 virtual | 2017-05-20 |     2
 full    | 2017-05-21 |     1
 virtual | 2017-05-21 |     1
 full    | 2017-05-22 |     3

如何将上述结果按created_at 分组以获得以下输出:

 created_at | full_count | virtual_count
------------+-----------------
 2017-05-20 |     2     |  2
 2017-05-21 |     1     |  1
 2017-05-22 |     3     |  0

我想在一行中按created_at 获取full 和virtual 类型计数。

【问题讨论】:

    标签: sql postgresql postgresql-9.5


    【解决方案1】:

    这应该可行:

    with so as (
    select type, created_at::date , count(type) from txns group by created_at::date, type order by created_at::date
    )
     select
      created_at
    , sum(case when type = 'full' then count else 0 end) full_count
    , sum(case when type = 'virtual' then count else 0 end) virtual_count
    from so
    group by created_at;
    
     created_at | full_count | virtual_count
    ------------+------------+---------------
     2017-05-20 |          2 |             2
     2017-05-21 |          1 |             1
     2017-05-22 |          3 |             0
    (3 rows)
    

    【讨论】:

    • 你太棒了,谢谢!等待其他结果,否则我会接受它非常感谢。
    【解决方案2】:

    我会在没有 CTE/子查询的情况下这样做:

    select created_at::date,
           sum( (type = 'Full')::int ) as cnt_full,
           sum( (type = 'Virtual')::int ) as cnt_virtual
    from txns
    group by created_at::date
    order by created_at::date;
    

    Postgres 经常实现 CTE,因此这甚至可能具有轻微的性能优势。

    注意:您还可以在更新的 Postgres 版本中使用 filter:

    select created_at::date,
           count(*) filter (where type = 'Full') as cnt_full,
           count(*) filter (where type = 'Virtual') as cnt_Virtual
    from txns
    group by created_at::date
    order by created_at::date;
    

    【讨论】:

    • 这个方案比较好,“type”不应​​该在组里。
    【解决方案3】:

    如果你有两种以上的类型,在进一步处理中你可以处理 hstore:

    WITH q AS ( SELECT type, created_at::date , count(type) FROM txns GROUP BY 1,2)
    SELECT created_at, hstore(array_agg(type), array_agg(count::text))
    FROM q GROUP BY 1;
    

    【讨论】:

      猜你喜欢
      • 2021-02-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-11
      • 1970-01-01
      相关资源
      最近更新 更多