在Postgresql中统计不同的日历周,月

时间:2014-10-01 09:23:50

标签: sql postgresql count query-optimization

我已经知道如何计算我的数据库中有多少天?

SELECT 
       COUNT(DISTINCT DATE (TIME)) AS distinct_days
FROM table;

但是当我尝试计算不同的数周或数月时,我发现的唯一解决方案是超慢......

几个月:

 SELECT 
       COUNT(DISTINCT CONCAT (EXTRACT(YEAR FROM TIME),EXTRACT(MONTH FROM TIME))) AS distinct_months
FROM table;

几周

SELECT 
       COUNT(DISTINCT CONCAT (EXTRACT(YEAR FROM TIME),EXTRACT(MONTH FROM TIME), EXTRACT(WEEK FROM TIME))) AS distinct_weeks
FROM table;

您有什么想法进行优化吗?

(更新)注意:

COUNT(DISTINCT DATE_TRUNC('week', time)) AS distinct_weeks 

 COUNT(DISTINCT CONCAT (EXTRACT(YEAR FROM TIME),EXTRACT(MONTH FROM TIME), EXTRACT(WEEK FROM TIME))) AS distinct_weeks

没有相同的结果(我想要第二个)!

使用COUNT(DISTINCT DATE_TRUNC('week', time)),您有53种可能性,COUNT(DISTINCT CONCAT (EXTRACT(YEAR FROM TIME),EXTRACT(MONTH FROM TIME), EXTRACT(WEEK FROM TIME)))可能是无限(例如2014-01第1周与2013-01第1周不同)......

2 个答案:

答案 0 :(得分:1)

最后,我发现了至少两倍的东西:

表示不同的周:

SELECT COUNT(distinct_weeks)
FROM (SELECT CONCAT(EXTRACT(YEAR FROM TIME),EXTRACT(MONTH FROM TIME),EXTRACT(WEEK FROM TIME)) AS distinct_weeks
      FROM table
      GROUP BY EXTRACT(YEAR FROM TIME),
               EXTRACT(MONTH FROM TIME),
               EXTRACT(WEEK FROM TIME)) t

不同月份:

SELECT COUNT(distinct_months)
FROM (SELECT CONCAT(EXTRACT(YEAR FROM TIME),EXTRACT(MONTH FROM TIME)) AS distinct_months
      FROM table
      GROUP BY EXTRACT(YEAR FROM TIME),
               EXTRACT(MONTH FROM TIME)) t

答案 1 :(得分:0)

也许简单地截断日期会更快,因为您不需要字符串转换和连接:

SELECT 
  COUNT(DISTINCT DATE_TRUNC('week', mytime)) AS distinct_weeks,
  COUNT(DISTINCT DATE_TRUNC('month', mytime)) AS distinct_months,
  COUNT(DISTINCT DATE_TRUNC('year', mytime)) AS distinct_years
FROM mytable;