【问题标题】:Summing sales dollars for most recent month and 2nd most recent month最近一个月和最近第二个月的销售额总和
【发布时间】:2022-11-10 06:45:43
【问题描述】:

对于 12 个月中的每一个月,我希望创建一个字段,根据当前日期在最近一个月和最近第二个月的帐户级别汇总销售额。

例如,假设今天的日期是 22 年 10 月 6 日,“MostRecentNovember”将汇总 2021 年 11 月的销售额。“2ndMostRecentNovember”将汇总 2020 年 11 月的销售额。一旦当前日期移至 2022 年 11 月,此查询将调整为从 2022 年开始拉动 MostRecentNovember 的销售额,从 2021 年开始拉动 2ndMostRecentNovember 的销售额。

相反,鉴于今天的日期是 22 年 10 月 6 日,“MostRecentJune”将汇总 2022 年 6 月的销售额,“2ndMostRecentJune”将汇总 2021 年 6 月的销售额。

下面是我对这段代码的尝试,我认为这部分存在,但不确定它是否正是我想要的

SELECT NovemberMostRecent_Value = 
       sum(case when datepart(year,tran_date) = datepart(year, getdate())
AND DATEPART(month, tran_date) = 11 then value else 0 end)
       NovemberSecondMostRecent_Value = 
       sum(case when datepart(year,tran_date) = datepart(year, getdate())-1
AND DATEPART(month, tran_date) = 11 then value else 0 end)

这是源数据表的sn-p

account_no tran_date value
123 11/22/21 500
123 11/1/21 500
123 11/20/20 1500
123 6/3/22 5000
123 6/4/21 2000
456 11/3/20 525
456 11/4/21 125

根据评论中的请求。所需结果表

account_no NovemberMostRecent November2ndMostRecent
123 1000 1500
456 125 525

【问题讨论】:

    标签: sql sql-server case getdate datepart


    【解决方案1】:

    你为什么不把过去两年的销售额按月和年分组?那不就解决问题了吗?

    或者,您可以显示一个表格,描述您想要实现的目标。

    【讨论】:

    • 我不知道如何才能更清楚地说明我想要实现的目标。我需要每个月和最近一年/最近第二年组合的单个字段。简单地求和然后按月/年分组并不能实现这一点。
    • 也许一张表来代表你想要的结果
    • 已添加到帖子...
    【解决方案2】:

    这应该可以正常工作。 注意:我只假设所有行的 account_no 都是相同的,如果它们不同,那么您需要将其作为条件传递给子查询。

    WITH CTE AS
    (SELECT (SELECT SUM(value) FROM tablename WHERE datepart(year, tran_date) = YEAR(getdate()) AND datepart(month, tran_date) = 11)
    AS first_value,
    (SELECT SUM(value) FROM tablename WHERE datepart(year, tran_date) = YEAR(getdate())-1 AND datepart(month, tran_date) = 11)
    AS second_value,
    (SELECT SUM(value) FROM tablename WHERE datepart(year, tran_date) = YEAR(getdate())-2 AND datepart(month, tran_date) = 11)
    AS third_value)
    SELECT IIF (first_value>0, first_value, second_value) AS NovemberMostRecent_Value,
    IIF (first_value>0, second_value, third_value) AS NovemberSecondMostRecent_Value FROM CTE;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-08-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-24
      • 1970-01-01
      相关资源
      最近更新 更多