【问题标题】:Oracle group orders by date and sum the totalOracle 按日期对订单进行分组并对总数求和
【发布时间】:2013-07-31 10:20:35
【问题描述】:

我的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 行,第一行所有 10 个订单的总和为 order_total,第二行row 当然会有order_total 31号的单单。

到目前为止我的尝试:

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:缺少表达式

我曾尝试使用来自 this question 的解决方案,但我认为它不太适合我的场景(这是我的 group by expression 的来源)。

【问题讨论】:

  • 为什么order_idselect 列表中;您希望在汇总 10 个订单的单行中显示什么?您要么需要删除它,要么将其替换为聚合函数。
  • 是的,我同意它不应该存在,删除它谢谢。现在错误变为ORA-00936: missing expression

标签: sql oracle group-by


【解决方案1】:

假设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 年 7 月 2013 年 6 月 30 日之前。

快速SQL Fiddle

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-02-07
    • 2022-12-22
    • 1970-01-01
    • 2015-06-26
    • 1970-01-01
    • 1970-01-01
    • 2021-11-01
    • 1970-01-01
    相关资源
    最近更新 更多