SQL模仿Excel

时间:2014-05-09 03:35:06

标签: sql sql-server sql-server-2005

我有一个财务问题,我们正试图将其放入SQLServer 2005数据库(默认安装)。我们正在进行从今年到去年同一季度的季度比较,即(2013Q1 - 2012Q1)/ 20132Q1 。如上所述,有人可以写一个查询来返回1到9之间的有序列表,其中季度超过四分之一吗?

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
提前致谢; - )

2 个答案:

答案 0 :(得分:0)

SQL查询中的大量格式化,但练习很有趣。通常,您应该将格式(例如舍入)提升到应用程序级别,但是因为您尝试模拟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

答案 1 :(得分:0)

我同意上面的评论,如果你拆分夸脱会更容易:

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 )

我的数字偏离你的,我没有调查原因,但它应该给你一个开始。