Question

I have an finance issue that we are trying to put into a SQLServer 2005 database (default installation). We are doing quarterly comparison from this year to the same quarter last year i.e. (2013Q1 - 2012Q1) / 20132Q1. Can someone write a query to return an ordered list from 1 - 9 with the quarter over quarter as described above?

In data set
QUART   REV
2011Q1  6,175,352 
2011Q2  6,591,067 
2011Q3  6,219,978 
2011Q4  6,189,939 
2012Q1  7,178,652 
2012Q2  6,731,467 
2012Q3  6,949,978 
2012Q4  6,679,939 
2013Q1  6,242,802 
2013Q2  6,421,902 
2013Q3  6,667,007 
2013Q4  6,575,004

Expected output
QUART   COMP
1   0.1625
2   0.0213
3   0.1174
4   0.0792
5   -0.1304
6   -0.0460
7   -0.0407
8   -0.0157
Thanks in advance ;-)

Était-ce utile?

La solution

I agree with the above comment, it is much easier if you split quart:

create table t ( yr int not null , qt int not null , salary int not null , primary key (yr,qt) )

insert into t (yr,qt,salary) values (2011,1,6175352) , (2011,2,6591067) , (2011,3,6219978) , (2011,4,6189939) , (2012,1,7178652) , (2012,2,6731467) , (2012,3,6949978) , (2012,4,6679939) , (2013,1,6242802) , (2013,2,6421902) , (2013,3,6667007) , (2013,4,6575004)

select row_number() over (order by yr, qt) as quart, comp from ( select t1.yr, t1.qt , (1.0*t1.salary - (select salary from t t2 where t2.yr = t1.yr - 1 and t2.qt = t1.qt) ) / t1.salary comp from t t1 where t1.yr >= 2012 )

my numbers deviates from yours, I have not investigate why but it should give you a start.

Autres conseils

Lot of formatting in a SQL query, but the exercise was fun. Normally, you should elevate formatting (such as rounding) to the application level, but since you're trying to emulate Excel...

/*sample data*/
DECLARE @T TABLE ( Quart CHAR(6), Rev INT )

INSERT  INTO @T
        ( Quart, Rev )
VALUES  ( '2011Q1', 6175352 ),
        ( '2011Q2', 6591067 ),
        ( '2011Q3', 6219978 ),
        ( '2011Q4', 6189939 ),
        ( '2012Q1', 7178652 ),
        ( '2012Q2', 6731467 ),
        ( '2012Q3', 6949978 ),
        ( '2012Q4', 6679939 ),
        ( '2013Q1', 6242802 ),
        ( '2013Q2', 6421902 ),
        ( '2013Q3', 6667007 ),
        ( '2013Q4', 6575004 );


/*query begins here 
    cte is used to parse quart column into years & quarters */

WITH    cte
          AS ( SELECT   Yr = CONVERT(SMALLINT, LEFT(Quart, 4))
                      , Qt = RIGHT(Quart, 1)
                      , Rev
               FROM     @T
             )
/*join cte to itself to compare last year same quarter
    ROW_NUMBER used to get sequential ordering
    CONVERT to numeric and rounding to get formatting
*/
    SELECT  QUART = ROW_NUMBER() OVER (ORDER BY b.Yr
          , b.Qt) , 
          COMP = CONVERT(NUMERIC(5,4), ROUND((a.Rev-b.Rev*1.0)/ b.Rev, 4))
    FROM    cte a
            JOIN cte b ON b.Qt = a.Qt
                          AND b.Yr = a.Yr - 1
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top