小编典典

SQL:仅将月份和年份列与日期进行比较

sql

我有一张桌子MonthlyShipments,看起来像:

partnumber | quantity | month | year |
part1      |       12 |     6 | 2011 |
part1      |       22 |     5 | 2011 |
part1      |       32 |     4 | 2011 |
part1      |       42 |     3 | 2011 |
part1      |       52 |     2 | 2011 |

我想对过去3个月(不包括当月)的数量求和。我的where子句当前看起来像:

where
  MonthlyShipments.Month <> MONTH(GETDATE()) AND 
  CAST(
    (CAST(MonthlyShipments.Month as nvarchar(2)) + 
    '-01-' + 
    CAST(MonthlyShipments.Year as nvarchar(4))) as DateTime)
  > DATEADD(m, -4, GETDATE())

它有效,但丑陋和侮辱。关于使其更漂亮有什么建议吗?非常感谢!


阅读 195

收藏
2021-05-23

共1个答案

小编典典

没什么好…

DATEDIFF(
    month,
    DATEADD(Year, MonthlyShipments.Year-1900,
        DATEADD(Month, MonthlyShipments.Month-1, 0)
           ),
    GETDATE()
    ) BETWEEN 1 AND 3

但是,可以将嵌套的DATEADD用作计算列和索引列

ALTER TABLE MonthlyShipments ADD
    ShipDate AS DATEADD(Year, MonthlyShipments.Year-1900,
            DATEADD(Month, MonthlyShipments.Month-1, 0)
               )

这使

WHERE DATEDIFF(month, ShipDate, GETDATE()) BETWEEN 1 AND 3
2021-05-23