简体   繁体   English

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

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

My Orders table looks like: 我的Orders表看起来像:

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

My goal is to get a set of rows where each row represents all orders on that date, so I'm trying to group the orders by date and get the sum of the order_total . 我的目标是获得一组行,其中每一行代表该日期的所有订单,因此我尝试按日期对订单进行分组并获取order_total的总和。 I'm also limiting the results by only selecting orders from the last 30 days. 我也只是通过选择过去30天的订单来限制结果。

To clarify, for example if there were 30 orders in the last 30 days all on unique days then I would get 30 rows in the result. 为了澄清,例如,如果在过去30天内有30个订单全部在唯一的日子里,那么我将在结果中得到30行。 Another example: if there were 10 orders on 30th July, and only 1 order on 31st July then I'm aiming to get 2 rows in the result set, with order_total summed for all 10 orders in the first row, and the second row would of course have the order_total of the single order on the 31st. 另一个例子:如果7月30日有10个订单,7月31日只有1个订单,那么我的目标是在结果集中获得2行, order_total汇总第一行中的所有10个订单,第二行将当然在31日有单一订单的order_total

My attempt so far: 我到目前为止的尝试:

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

This gives an error: 这给出了一个错误:

ORA-00936: missing expression ORA-00936:缺少表达

I have tried to use the solution from this question but I don't think it quite fits for my scenario (this is where my group by expression has come from). 我试图使用这个问题的解决方案,但我不认为它非常适合我的场景(这是我的表达式来自的地方)。

Assuming order_id should not be there, and that created_date has a time component (which seems likely as it's a timestamp ), you need to truncate the date to remove the time when doing the aggregation: 假设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

I've also applied trunc to the where clause, otherwise it would ignore any orders 30 days ago between midnight and whatever time you ran the query today. 我还将trunc应用于where子句,否则它将在30天前的午夜之间以及今天运行查询的任何时间忽略任何订单。 And I've used the trunc'd date directly in the order by , rather than the column alias, so that the order is right when you go across a month-end - ordering by the DD/MM/YYYY string value would put 01/07/2013 before 30/06/2013, for example. 我直接按order by使用截断日期,而不是列别名,这样当你跨越月末时顺序是正确的 - 按DD/MM/YYYY字符串值排序将放01例如,在2013年6月30日之前的/ 07/2013。

Quick SQL Fiddle . 快速SQL小提琴

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

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