【问题标题】:Join two columns as a date in sql在sql中加入两列作为日期
【发布时间】:2020-02-26 22:03:20
【问题描述】:

我目前正在通过 Microsoft Query 处理一份报告,我遇到了这个问题,我需要计算过去一年的总金额。

表格如下所示:

Item Number | Month | Year | Amount |
...........PAST YEARS DATA...........
  12345     |   1   | 2019 |   10   |
  12345     |   2   | 2019 |   20   |
  12345     |   3   | 2019 |   15   |
  12345     |   4   | 2019 |   12   |
  12345     |   5   | 2019 |   11   |
  12345     |   6   | 2019 |   12   |
  12345     |   7   | 2019 |   12   |
  12345     |   8   | 2019 |   10   |
  12345     |   9   | 2019 |   10   |
  12345     |   10  | 2019 |   10   |
  12345     |   11  | 2019 |   10   |
  12345     |   12  | 2019 |   10   |
  12345     |   1   | 2020 |   10   |
  12345     |   2   | 2020 |   10   |

您将如何计算商品编号12345 从 02-2019 到 02-2020 的总金额?

【问题讨论】:

  • 你想要这个东西在 SQL 还是 Excel 中?
  • 最好在 SQL 中! :)
  • @WhyMyCodeLong:那么,请用您正在使用的数据库标记您的问题。

标签: sql sql-server excel tsql date


【解决方案1】:

假设您正在运行 SQL Server,您可以使用 datefromparts() 重新创建一个 date 并将其用于过滤:

select sum(amount)
from mytable
where 
    itemnumber = 12345
    and datefromparts(year, month, 1) >= '20190201'
    and datefromparts(year, month, 1) < '20200301'

【讨论】:

  • 是否可以动态运行此查询?我可以使用 getdate() 代替“20200301”吗?
  • 你可以使用类似的东西:datefromparts(year, month, 1) between DATEADD(year,-1,GETDATE()) and GETDATE()
  • 您好 GMB,对于延迟回复感到抱歉。代码完美运行。非常感谢!还要感谢@CR7SMS 的动态代码。
【解决方案2】:

你也可以用这个

 SELECT sum(amount) as Amount
 FROM YEARDATA
 WHERE ( Month >=2 and year = '2019')
 or ( Month <=2 and year = '2020')
 and ItemNumber = '12345'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-01
    • 1970-01-01
    相关资源
    最近更新 更多