【问题标题】:Database Query with 3 Months Current Year and Previous Year查询当年和上年 3 个月的数据库
【发布时间】:2021-12-17 22:41:34
【问题描述】:

希望不要过度思考这个......

我目前正在寻找有关此的任何指示。我有一张桌子/视图

|Cust_ID | CName | Inv_Date   | Sales
|01A     | A     | 2/7/2006   | 20
|02A     | B     | 2/7/2006   | 10
|01A     | A     | 11/5/2005  | 15

每个客户在不同日期都有很多发票
然后我想用 sales for

提取每个客户
  • 当前年份的三个(月)(例如 2006 年)。这是今天日期的前 3 个月。
    Inv_Date >= add_months(trunc(sysdate, 'month'), -3)
    and Inv_Date <= add_months(last_day(sysdate), -1)
    
  • 与上一年(2005 年)的三 (3) 个月相同?!

假设类似

|Cust_ID | CName | CY_Sum_Sales | PY_Sum_Sales
|01A     | A     | 20           | 15
|02A     | B     | 0            | 0

假设“sysdate”是 2008 年 1 月 8 日。以下是我的试用版

select Customer_No, Customer_Name,
   TO_CHAR(SUM(Sales_Colmn), 'fm999G999G999G999G999D0') as "TYear_Sale",
    
 TO_CHAR((SELECT SUM(Sales_Colmn) from cust_table CL
 where CL.invoice_date BETWEEN add_months(trunc(to_date('&From_Dt', 'DD/MM/YYYY'), 'mm'), -(3 + 12)) --15 months
   and add_months(trunc(to_date('&To_Dt', 'DD/MM/YYYY'), 'mm'), -(1 + 12)) --13 months) 
   and Customer_No = CL.Customer_No), 'fm999G999G999G999G999D0') as "LYear_Sale"
from cust_table
where invoice_date BETWEEN add_months(trunc(to_date('&From_Dt', 'DD/MM/YYYY'), 'mm'), -3) --3 months
  and add_months(trunc(to_date('&To_Dt', 'DD/MM/YYYY'), 'mm'), -1) --1 months)
 GROUP BY Customer_No, Customer_Name
 ORDER BY 3

但是运行时间太长了。一定是做错了什么

【问题讨论】:

  • MySQL 不是 Oracle,Oracle 也不是 MySQL。请检查标签描述并删除其中一个。
  • 另外请展示您当前的尝试并描述它有什么问题
  • 您的Inv_Date 数据类型是什么?它看起来像 char 或某种字符串数据类型。如果是这样,你不应该将日期存储为字符串,你应该使用日期/日期时间数据类型
  • @nacho 这是日期

标签: oracle date


【解决方案1】:

您使用的函数(add_monthssysdate)表明这是 Oracle。

由于您想回到上一年的同一个月,您只需再增加(好的,减去)12 个月。像这样的:

SQL> select trunc(sysdate) c_today,
  2         trunc(sysdate, 'mm') c_trunc_today,
  3         --
  4         add_months(trunc(sysdate, 'mm'), -3) c_3_months_ago,
  5         add_months(trunc(sysdate, 'mm'), -1) c_1_month_ago,
  6         --
  7         add_months(trunc(sysdate, 'mm'), -(3 + 12)) c_15_months_ago,
  8         add_months(trunc(sysdate, 'mm'), -(1 + 12)) c_13_months_ago
  9  from dual;                                    ^^
                                                   this!
C_TODAY    C_TRUNC_TO C_3_MONTHS C_1_MONTH_ C_15_MONTH C_13_MONTH
---------- ---------- ---------- ---------- ---------- ----------
03.11.2021 01.11.2021 01.08.2021 01.10.2021 01.08.2020 01.10.2020
                      --------------------- =====================
                      this year             previous year, same months

SQL>

【讨论】:

  • 在@Littlefoot 回复后添加了试用版
猜你喜欢
  • 2012-07-13
  • 2019-12-18
  • 2014-10-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-09
相关资源
最近更新 更多