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

时间:2011-06-08 18:50:50

标签: sql sql-server tsql sql-server-2008r2-express

我有一张表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())

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

4 个答案:

答案 0 :(得分:5)

好多了......

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

答案 1 :(得分:1)

您可以添加日期列吗?如果您需要进行日期计算,并且您不希望事情变得丑陋,这可能是一项要求。即使computed column也可行......

然后你可以做这样的事情:

WHERE datecolumn < DATEADD(month, -3, GETDATE())

答案 2 :(得分:0)

您可以将月份+日期转换为date,然后将其与当前日期进行比较:

WHERE DATEDIFF(m,CONVERT(DATE, [month]+'/01/'+[year],101), GETDATE()) 
BETWEEN 1 AND 3

或者正如其他人所说,您可以创建一个包含date类型

的新计算列

答案 3 :(得分:0)

如果您有(year,month)索引,我会考虑使用它:

FROM MonthlyShipments ms
WHERE ( ms.year = YEAR(GetDate()) 
        AND ms.month BETWEEN MONTH(GetDate())-3
                         AND MONTH(GetDate())-1
      )
   OR ( ms.year = YEAR(GetDate())-1
        AND ms.month BETWEEN 12 + MONTH(GetDate())-3
                         AND 12 + MONTH(GetDate())-1
      ) 

虽然看起来并不漂亮。