【问题标题】:Historic and avg data in sqlsql中的历史数据和平均数据
【发布时间】:2021-08-25 06:11:15
【问题描述】:

我想使用下面提供的示例表在以下场景中获取报告数据(我的数据库中的数据很大)

  1. 列出项目(同一周,上一年)销售额和(同一天,同一周,上一年)销售额。
  2. 滚动 6 个月平均每周销售量
id date_week date_value sales
Item1 2020/01-04 20200120 230
Item2 2020/06-03 20200608 23.0
Item3 2019/11-03 20191111 null
Item4 2020/07-04 20200720 123
Item5 2019/08-01 20190729 456
Item6 2019/09-03 20190909 1234
Item7 2020/06-02 20200601 4556
Item8 2020/09-01 20200824 23
Item9 2021/09-02 20210906 1223

在上面的表格中 date_week 是年/月_周(所以我在这里得到周数)

我正在尝试以下查询来实现

SELECT
  DATEPART(week, date_value) AS Week,
  id ,
  sum(sales) AS sales
FROM table
WHERE date_value <= date_value
 AND date_value < DATEADD(year, 1, date_value)
GROUP BY DATEPART(week, date_value), id
ORDER BY DATEPART(week, date_value);

请建议我如何实现我正在寻找的场景。

【问题讨论】:

  • 您正在混合数周和数月。这需要很多解释。请准确解释结果是什么样的,以及如何处理“6 个月”不是确切的周数这一事实。
  • @GordonLinoff,忽略 date_week 以及如何使用普通日历获得 6 个月的平均销售量
  • 我认为这里仍然存在一些混乱。您的示例代码建议的日期范围为 1 年 (WHERE date_value &lt;= date_value AND date_value &lt; DATEADD(year, 1, date_value)),但您之前的评论要求“平均 6 个月”。此外,您可能需要提供源表的示例和/或模式,以便我们知道我们正在处理的类型。最后,“6 个月平均每周销售”没有多大意义。您是否希望将六个月内的所有销售额加起来,然后通过将该总数除以 [[然而六个月内发生多少周]] 来获得每周平均值?谢谢
  • @ChrisWalsh,我的错误无法解释我的问题陈述。实际上我正在寻找“6 个月滚动平均”。

标签: sql sql-server database tsql sql-date-functions


【解决方案1】:
  1. 您可以通过加入来完成这些操作。首先,我将日期列分隔为 Year |月 |周 |日。如果这是您唯一可用的日期格式,您可以使用 left()、right() 函数。拥有日期时间格式总是更好。

您的查询可能如下所示:

SELECT t1.Year, t1.Week, t1.Id, t1.Sales, t2.Sales as Last_year_this_week_sales
from (
    SELECT
      cast(right(date_value,2) as int) AS Week,
      cast(left(date_value,4) as int) as Year
      id ,
      sum(sales) AS sales
    FROM table
    GROUP BY right(date_value,2),
    left(date_value,4), id ) t1
left join  (
    SELECT
      cast(right(date_value,2) as int) AS Week,
      cast(left(date_value,4) as int) as Year
      id ,
      sum(sales) AS sales
    FROM table
    GROUP BY right(date_value,2),
    left(date_value,4), id ) t2 ON t1.week = t2.week and t2.year = t1.year-1 and t1.id = t2.id';

我假设您希望获得 id 级别的结果。如果没有,您需要将其从您的分组中删除并加入。您可以对每日结果执行相同的操作,将周改为日。

  1. 您可以使用子查询 - 如果您需要获取过去 6 个月内每周总计的平均值。同样,如果您在项目级别需要它,请将 id 保留在您的 select 和 group by 语句中。

如果没有,你可以这样做:

SELECT avg(sales) as Sales_avg  
FROM 
    (SELECT
    cast(right(date_value,2) as int) AS Week,
    cast(left(date_value,4) as int) as Year,
    sum(sales) AS sales
    FROM table
    where date_value>='20210101' --replace with the date you need
    GROUP BY right(date_value,2),
    left(date_value,4) ) t1;

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-04-13
  • 1970-01-01
  • 2019-06-22
  • 1970-01-01
  • 2017-03-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多