1

以下のように、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)a を実行するため、これを行うことはできません。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 があまり役に立たないので、ただの苦痛です。UNION2 つのクエリが必要で、それらをアウターでラップします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 に答える