1

我有由 SQL TABLE A 生成的下表

timeinterval   count(exclusive range)
0-6             2
0-12            5
0-18            10

我想要一张像这样的桌子 TABLE B

timeinterval   count(exclusive range)  count(inclusive range)
1-6             2                       2
1-12            5                       3
1-18            10                      5

我已经生成了表 A 并且需要表 B。我可以在 SQL 中做一些事情,我可以在代码中为表 A 添加一个查询,并对表中的第二行执行类似 (0-12)-(0-6) 的操作B.

用于生成表 A 的代码是

with ranges as 
  (
    select 6 as val, 1 as count_all
 union all
    select 12, 1
    union all
    select 18, 1
    union all
 select 24, 1
    union all
 select 30, 1
    union all  
 select 36, 1
    union all 
 select 42, 1
    union all
 select 48, 1
    union all   
 select 1, 0
  )
select case when ranges.count_all = 0
            then 'more'
            else  convert (varchar(10), ranges.val) 
        end [MetLifeExperienceMonths],
       sum (case when (ranges.count_all = 0 and GoldListHistogram.MetLifeExperienceMonths>=1)
                   or
           (GoldListHistogram.MetLifeExperienceMonths<= ranges.val and  GoldListHistogram.MetLifeExperienceMonths>=1)
                 then 1 end) [count],
count(EmployeeID) as 'Total'
into yy
from GoldListHistogram
cross join ranges
where MetLifeExperienceMonths > 0
group by ranges.val, ranges.count_all

我需要修改查询,以便我可以从第二行开始的每一行减去“计数(不包括范围)”的前两行值。就像 0-12(时间间隔)行一样,我需要输出一个值是前两行的差异..like row(i)=count(i)-count(i-1)。

第一列给出了 5 年的时间间隔(以月为单位)第二列计算没有。独家范围内的员工人数,例如 (0-6,0-12,0-18)..6 ,12,18 是没有。月数第三列计算没有。专属范围内的员工人数(0-6,6-12,12-18)

4

1 回答 1

0

你不能只为范围添加一个起始值吗?就像是:


with ranges as 
  (
    select 6 as val, 0 as start, 1 as count_all
 union all
    select 12, 7, 1
    union all
    select 18, 13, 1
    union all
 select 24, 19, 1
    union all
 select 30, 25, 1
    union all  
 select 36, 31, 1
    union all 
 select 42, 37, 1
    union all
 select 48, 43, 1
    union all   
 select 1, 49, 0
  )
select case when ranges.count_all = 0
            then 'more'
            else  convert (varchar(10), ranges.val) 
        end [MetLifeExperienceMonths],
       sum (case when (ranges.count_all = 0 and GoldListHistogram.MetLifeExperienceMonths>=1)
                   or
           (GoldListHistogram.MetLifeExperienceMonths=1)
                 then 1 else 0 end) [count inclusive],
       sum (case when (ranges.count_all = 0 and GoldListHistogram.MetLifeExperienceMonths>=1)
                   or
           (GoldListHistogram.MetLifeExperienceMonths=ranges.start)
                 then 1 else 0 end) [count exclusive],
count(EmployeeID) as 'Total'
into yy
from GoldListHistogram
cross join ranges
where MetLifeExperienceMonths > 0
group by ranges.val, ranges.count_all;

于 2012-09-27T08:24:40.290 回答