SQL: Comparing Dates with only Month and Year columns

anonymous picture anonymous · Jun 8, 2011 · Viewed 11.7k times · Source

I have a table MonthlyShipments that looks like:

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

I want to sum the quantities of the past 3 months, excluding the current month. My where clause currently looks like:

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())

It works, but its ugly and insulting. Any advice on making it prettier? Much appreciate!

Answer

gbn picture gbn · Jun 8, 2011

Not much better...

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

however the nested DATEADD can be made a computed and indexed column

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

which gives

WHERE DATEDIFF(month, ShipDate, GETDATE()) BETWEEN 1 AND 3