繁体   English   中英

Oracle组按日期排序并总计总和

[英]Oracle group orders by date and sum the total

我的Orders表看起来像:

order_id     (number)
order_total  (number)
created_date (timestamp)
status       (varchar2)

我的目标是获得一组行,其中每一行代表该日期的所有订单,因此我尝试按日期对订单进行分组并获取order_total的总和。 我也只是通过选择过去30天的订单来限制结果。

为了澄清,例如,如果在过去30天内有30个订单全部在唯一的日子里,那么我将在结果中得到30行。 另一个例子:如果7月30日有10个订单,7月31日只有1个订单,那么我的目标是在结果集中获得2行, order_total汇总第一行中的所有10个订单,第二行将当然在31日有单一订单的order_total

我到目前为止的尝试:

select
  sum(order_total) total_amount,
  to_char(created_date, 'DD/MM/YYYY') grouped_date
from
  orders
where
  status = 'Complete' and
  created_date >= (sysdate-30)
group by
  to_char(created_date, 'DD'), to_char(created_date, 'MM'), to_char(created_date, 'YYYY')
order by
  created_date asc

这给出了一个错误:

ORA-00936:缺少表达

我试图使用这个问题的解决方案,但我不认为它非常适合我的场景(这是我的表达式来自的地方)。

假设order_id不应该存在,并且created_date有一个时间组件(看起来可能是timestamp ),您需要截断日期以删除进行聚合的时间:

select
  sum(order_total) as total_amount,
  to_char(trunc(created_date), 'DD/MM/YYYY') as grouped_date
from
  orders
where
  status = 'Complete' and
  created_date >= trunc(sysdate-30)
group by
  trunc(created_date)
order by
  trunc(created_date) asc

我还将trunc应用于where子句,否则它将在30天前的午夜之间以及今天运行查询的任何时间忽略任何订单。 我直接按order by使用截断日期,而不是列别名,这样当你跨越月末时顺序是正确的 - 按DD/MM/YYYY字符串值排序将放01例如,在2013年6月30日之前的/ 07/2013。

快速SQL小提琴

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM