Updating a Temp Table column with data from another column in same Temp Table (data from previous month)

  • Using T-SQL (SS2K8) in a stored procedure, I have created a temp table (#Month) with (Month, Year, Department, Count1, Count2, CurrPerc, and PrevPerc)

    I am trying to update that table with data (CurrPerc) from the previous month in the new column (the previous month's data in PrevPerc)

    UPDATE #Month

    SET [PrevPerc] = [CurrPerc]

    WHERE [MONTH] = (IF [MONTH] = 1 THEN 12 ELSE [MONTH] - 1 END

    WHEN [MONTH] = 1 THEN T.[YEAR] - 1 ELSE T.[YEAR] END

    INNER JOIN #Month P ON [DEPARTMENT] = P.DEPARTMENT

    I know my T-Sql is off, so any help would be great. Thanks!

  • Something like this?

    UPDATE #Month

    SET [PrevPerc] = [CurrPerc],

    [MONTH] = case [MONTH] when 1 THEN 12 ELSE [MONTH] - 1 END,

    [YEAR] = case [MONTH] when 1 THEN T.[YEAR] - 1 ELSE T.[YEAR] END

    If that doesn't get you close enough to figure it out I would recommend you take a few minutes and read the first article in my signature for best practices when posting questions.

    _______________________________________________________________

    Need help? Help us help you.

    Read the article at http://www.sqlservercentral.com/articles/Best+Practices/61537/ for best practices on asking questions.

    Need to split a string? Try Jeff Modens splitter http://www.sqlservercentral.com/articles/Tally+Table/72993/.

    Cross Tabs and Pivots, Part 1 – Converting Rows to Columns - http://www.sqlservercentral.com/articles/T-SQL/63681/
    Cross Tabs and Pivots, Part 2 - Dynamic Cross Tabs - http://www.sqlservercentral.com/articles/Crosstab/65048/
    Understanding and Using APPLY (Part 1) - http://www.sqlservercentral.com/articles/APPLY/69953/
    Understanding and Using APPLY (Part 2) - http://www.sqlservercentral.com/articles/APPLY/69954/

  • Thanks Sean - that populated the PrevPerc column with the data from the CurrPerc (but from the same month). I was hoping to capture the previous month's CurrPerc data.

    It has gotten me closer though... I'll keep at it.

    Jeff

  • UPDATE CurrMonth

    SET [PrevPerc] = PrevMonth.[CurrPerc]

    FROM #Month CurrMonth

    INNER JOIN #Month PrevMonth ON

    PrevMonth.[DEPARTMENT] = CurrMonth.DEPARTMENT AND

    PrevMonth.[YEAR] = CurrMonth.[YEAR] - CASE WHEN CurrMonth.[MONTH] = 1 THEN 1 ELSE 0 END AND

    PrevMonth.[MONTH] = CASE WHEN CurrMonth.[MONTH] = 1 THEN 12 ELSE CurrMonth.[MONTH] - 1 END

    SQL DBA,SQL Server MVP(07, 08, 09) A socialist is someone who will give you the shirt off *someone else's* back.

  • That was it! Thank you so much Scott.

Viewing 5 posts - 1 through 4 (of 4 total)

You must be logged in to reply to this topic. Login to reply