【问题标题】:Can we add COUNT as a column in the result set?我们可以在结果集中添加 COUNT 作为列吗?
【发布时间】:2020-12-19 14:08:31
【问题描述】:

我有一个大查询,它有不同的结果数据。

我想知道是否可以添加一个 COUNT 列来计算总结果计数并显示为一列。

假设我有以下来自我的大查询的结果

col_12_0_|ppi_event_id|col_1_0|col_11_0_|col_13_0_|col_14_0_|col_15_0_|col_17_0| 
---------|------------|-------|---------|---------|---------|---------|--------| 
    27981|        3249| 149056|IN       |ongoing  |true     |Asia     |       0| 
    27989|        3249| 149060|FUR      |ongoing  |false    |Asia     |       1| 

预期结果如下。在总记录末尾添加计数列。

如果我总共有 10000 条记录,则计数在每列前面显示 10000 条。

col_12_0_|ppi_event_id|col_1_0|col_13_0_|col_14_0_|col_15_0_|col_17_0_|Count    |
---------|------------|-------|---------|---------|---------|---------|--------|
    27981|        3249| 149056|ongoing  |true     |Asia     |       0 |2       |
    27989|        3249| 149060|ongoing  |false    |Asia     |        1|2       |

【问题讨论】:

    标签: postgresql


    【解决方案1】:

    是的,使用count(*) over () 作为表达式。一个小例子:

    testdb=# with fake_data as (
    select 'foo' as col1, 'bar' as col2 union all
    select 'foo', 'baz')
    select *, count(*) over () AS total_rows_returned from fake_data;
     col1 | col2 | total_rows_returned 
    ------+------+---------------------
     foo  | bar  |                   2
     foo  | baz  |                   2
    (2 rows)
    

    【讨论】:

      猜你喜欢
      • 2018-07-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-16
      相关资源
      最近更新 更多