Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/date/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PostgreSQL选择数字总和,按日期分组_Postgresql_Date_Common Table Expression - Fatal编程技术网

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

PostgreSQL选择数字总和,按日期分组,postgresql,date,common-table-expression,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

我不确定是否已经存在类似的问题,无法找到我的解决方案,因此,如果这是重复的,很抱歉: 我有一张有日期的桌子:

  |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          |
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";
我在考虑做一个CTE类型的查询,因为在数据库中,我存储的东西是datetime,没有时区,还有一堆税 这是我的查询的开始:

 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
 )

这给了我一张最上面的桌子。最好的方法是什么?是通过“平均日期”来实现的吗?

这就是最终的效果:

 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;

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

  |date (date)| tax (numeric) |  (stuff in brackets is the type)
  |2012-12-12 | 15.00         |
  |2012-12-13 | 2.00          |
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";
选择
datetime::日期为“日期”,
总额(税)
来自suezensalon.的收据
其中datetime>=“2012-12-12 00:00:00”
日期时间<'2012-12-19 00:00:00'
按日期分组时间::日期
按“日期”订购;

在查询中有datetime,但在示例数据中有datetime。是吗?是的,它是正确的,我在cte中把它作为一个日期。当你真的想在开放或半开放的时间间隔内工作时,你不应该使用BETWEEN,只能在封闭的时间间隔内使用BETWEEN。如果您的时间间隔未结束,请对端点进行单独检查。