1

是否有一个函数可以计算整个月份的总数,如下所示?我不确定postgres是否。我正在寻找总价值。

2012-08=# select date_trunc('day', time), count(distinct column) from table_name group by 1 order by 1;

     date_trunc      | count 
---------------------+-------
 2012-08-01 00:00:00 |    22
 2012-08-02 00:00:00 |    34
 2012-08-03 00:00:00 |    25
 2012-08-04 00:00:00 |    30
 2012-08-05 00:00:00 |    27
 2012-08-06 00:00:00 |    31
 2012-08-07 00:00:00 |    23
 2012-08-08 00:00:00 |    28
 2012-08-09 00:00:00 |    28
 2012-08-10 00:00:00 |    28
 2012-08-11 00:00:00 |    24
 2012-08-12 00:00:00 |    36
 2012-08-13 00:00:00 |    28
 2012-08-14 00:00:00 |    23
 2012-08-15 00:00:00 |    23
 2012-08-16 00:00:00 |    30
 2012-08-17 00:00:00 |    20
 2012-08-18 00:00:00 |    30
 2012-08-19 00:00:00 |    20
 2012-08-20 00:00:00 |    24
 2012-08-21 00:00:00 |    20
 2012-08-22 00:00:00 |    17
 2012-08-23 00:00:00 |    23
 2012-08-24 00:00:00 |    25
 2012-08-25 00:00:00 |    35
 2012-08-26 00:00:00 |    18
 2012-08-27 00:00:00 |    16
 2012-08-28 00:00:00 |    11
 2012-08-29 00:00:00 |    22
 2012-08-30 00:00:00 |    26
 2012-08-31 00:00:00 |    17
(31 rows)
--------------------------------
      Total          |    12345
4

2 回答 2

4

尽我所能从您的问题和评论中猜出您想要按月计算不同计数的小计。你不能这样做,group by date_trunc('month',time)因为那会在所有日子里做一个count(distinct column)不同的事情。

为此,您需要一个子查询或 CTE:

WITH day_counts(day,day_col_count) AS (
  select date_trunc('day', time), count(distinct column)
  from table_name group by 1
)
SELECT 'Day', day, day_col_count
FROM day_counts
UNION ALL
SELECT 'Month', date_trunc('month', day), sum(day_col_count)
FROM day_counts
GROUP BY 2
ORDER BY 2;

我之前的评论之前的猜测是:按月分组?

select date_trunc('month', time), count(distinct column)
from table_name
group by date_trunc('month', time)
order by time

或者您是否尝试包括运行总计或小计行?对于运行总计,您需要sum用作窗口函数。小计只是一种痛苦,因为 SQL 并不真正适合它们。您需要UNION两个查询,然后将它们包装在一个外部ORDER BY.

于 2012-10-24T23:24:24.447 回答
1
select
    date_trunc('day', time)::text as "date",
    count(distinct column) as count
from table_name
group by 1
union
select
    'Total',
    count(distinct column)
from table_name
group by 1, date_trunc('month', time)
order by "date" = 'Total', 1
于 2012-10-24T23:40:31.803 回答