PostgreSQL选择数字总和,按日期分组

时间:2012-12-21 02:05:36

标签: postgresql date common-table-expression

我不确定那里是否有这样的问题,找不到我的解决方案,很抱歉,如果这是重复的话: 我有一张日期表:

  |date (date)| tax (numeric) |  (stuff in brackets is the type)
  |2012-12-12 | 5.00          |
  |2012-12-12 | 10.00         |
  |2012-12-13 | 2.00          |

我希望我的输出看起来像这样:

  |date (date)| tax (numeric) |  (stuff in brackets is the type)
  |2012-12-12 | 15.00         |
  |2012-12-13 | 2.00          |

我正在考虑做一个CTE类型的查询,因为在数据库中,我将事物存储为没有时区的日期时间,以及一堆税 这是我的查询的开始:

 with date_select as
 (
 select CAST(r.datetime as DATE), sum(r.tax) as tax
 from suezensalon.receipt r
 where r.datetime between '2012-12-12 00:00:00' and '2012-12-18 23:59:59'
 group by r.datetime  
 order by r.datetime
 )

这给了我顶级表格。做这个的最好方式是什么?是通过'平均日期'吗?

2 个答案:

答案 0 :(得分:1)

这就是最终的工作:

 with date_select as
 (
 select CAST(r.datetime as DATE), sum(r.tax) as tax
 from suezensalon.receipt r
 where r.datetime between '2012-12-12 00:00:00' and '2012-12-18 23:59:59'
 group by r.datetime  
 order by r.datetime 
 ) 
 select extract(Month from datetime) || '-' || extract(Day from datetime) || '-' ||   extract(Year from datetime) as Date, sum(tax)
 from date_select
 group by Date
order by Date;

答案 1 :(得分:0)

我认为最简单的选择,并且最有可能在索引存在的情况下表现良好,将是这样的:

SELECT
    datetime::date as "Date",
    sum(tax)
  FROM suezensalon.receipt
  WHERE datetime >= '2012-12-12 00:00:00'
    AND datetime <  '2012-12-19 00:00:00'
  GROUP BY datetime::date
  ORDER BY "Date";