2011-10-31 66 views
0

我的表中的记录是像下面如何计算记录之间的差异?

ym cnt 
200901 57 
200902 62 
200903 67 
... 
201001 84 
201002 75 
201003 75 
... 
201101 79 
201102 77 
201103 80 
... 

我想电脑当前的月份每月之间以及差异。 结果想下面......

ym cnt  diff 
200901 57  57 
200902 62  5 (62 - 57) 
200903 67  5 (67 - 62) 
... 
201001 84  ... 
201002 75 
201003 75 
... 
201101 79 
201102 77 
201103 80 
... 

谁能告诉我如何写一个SQL来得到结果,并且有着不错的表现?

UPDATE:

对不起简单的话

我的解决办法是

step1: input the currentmonth data into temp table1 

step2: input the permonth data into temp table2 

step3: left join 2 tables to compute the result 

Temp_Table1

SELECT (ym - 1) as ym , COUNT(item_cnt) as cnt 
FROM _table 
GROUP BY (ym - 1) 
order by ym 

Temp_Table2

SELECT ym , COUNT(item_cnt) as cnt 
FROM _table 
GROUP BY ym 
order by ym 



select ym , (b.cnt - a.cnt) as diff from Temp_Table2 a 
      left join Temp_Table1 b 
       on a.ym = b.ym 

* 如果我要比较今年和去年 月间差异,我只能改变YM - 1至YM - 100 *

但实际上,该组来者皆是不仅YM

有最多15个按键和最大100百万记录

所以,我不知道一个很好的解决方案可以轻松管理源

和良好的表现。

+0

可能的问题,如[这里](HTTP ://stackoverflow.com/questions/7794590/how-to-version-dynamic-business-objects-data)可能会帮助你 – linuxeasy

回答

1

对于MSSQL,这有一个参照表,所以可能它可以更快(也许不是),比左侧加入哪个引用了两个表:

-- ================ 
-- sample data 
-- ================ 
declare @t table 
(
    ym varchar(6), 
    cnt int 
) 

insert into @t values ('200901', 57) 
insert into @t values ('200902', 62) 
insert into @t values ('200903', 67) 
insert into @t values ('201001', 84) 
insert into @t values ('201002', 75) 
insert into @t values ('201003', 75) 

-- =========================== 
-- solution 
-- =========================== 
select 
    ym2, 
    diff = case when cnt1 is null then cnt2 
     when cnt2 is null then cnt1 
     else cnt2 - cnt1 
     end 
from 
(
    select 
     ym1 = max(case when k = 2 then ym end), 
     cnt1 = max(case when k = 2 then cnt end), 
     ym2 = max(case when k = 1 then ym end), 
     cnt2 = max(case when k = 1 then cnt end) 
    from 
    (
     select 
      *, 
      rn = row_number() over(order by ym) 
     from @t 
    ) t1 
    cross join 
    (
     select k = 1 union all select k = 2 
    ) t2 
    group by rn + k 
) t 
where ym2 is not null 
+0

感谢您的良好解决方案! – shenhengbin

0

谁能告诉我如何写一个SQL来得到结果

绝对。只需获取下一个最高日期的行,然后减去。

并且有很好的表现?

不。关系数据库并非真正意义上的线性遍历,甚至使用适当的索引也需要虚拟线性遍历。

相关问题