create YTD in a Table

  • CREATE TABLE #Table(

    [cod] [nchar](10) NULL,

    [year] [int] NULL,

    [month] [tinyint] NULL,

    [value] [float] NULL

    ) ON [PRIMARY]

    insert into #Table values ('cod1',2011,1,100)

    insert into #Table values ('cod1',2011,2,150)

    insert into #Table values ('cod1',2011,3,200)

    insert into #Table values ('cod1',2012,1,100)

    insert into #Table values ('cod1',2012,2,180)

    --insert into #Table values ('cod1',2012,3,180)

    --insert into #Table values ('cod1',2012,4,180)

    select cod,year,month,sum(value) val

    into #temp1 from

    (select * from #Table t2

    UNION

    select t2.cod,T2.year+1,t2.month,'' ppy from #Table t2

    WHERE T2.month not in(select isnull(t5.month,0) as month from #Table t5 where (T2.year-1)=T5.year)

    )k

    group by cod,year,month

    select cod,year,month,CASE WHEN val<>0 THEN val END val,(select SUM(t1.val) from #temp1 t1 WHERE (T2.year-1)=T1.year AND T2.month>=T1.month) AS PPY from #temp1 T2

    where t2.year in(select year from #Table)

  • ScottPletcher (9/5/2012)


    Since the table already contains the previous year's YTD totals, would a simple LEFT JOIN suffice to get the prior year's YTD total?

    SELECT

    t1curr.cod, t1curr.[year], t1curr.[month], t1curr.value, t1prev.value

    FROM dbo.Table_1 t1curr

    LEFT OUTER JOIN dbo.Table_1 t1prev ON

    t1prev.cod = t1curr.cod AND

    t1prev.[year] = t1curr.[year] - 1 AND

    t1prev.[month] = t1curr.[month]

    Assuming "cod" - whatever it is - doesn't change from year to year. If it's a stock ID then the assumption is optimistic.

    “Write the query the simplest way. If through testing it becomes clear that the performance is inadequate, consider alternative query forms.” - Gail Shaw

    For fast, accurate and documented assistance in answering your questions, please read this article.
    Understanding and using APPLY, (I) and (II) Paul White
    Hidden RBAR: Triangular Joins / The "Numbers" or "Tally" Table: What it is and how it replaces a loop Jeff Moden

Viewing 2 posts - 16 through 16 (of 16 total)

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