在同一个表中包含包容性和排他性范围

时间:2012-09-27 06:57:14

标签: sql sql-server sql-server-2008 ssrs-2008

我有SQL TABLE A生成的下表

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

我想要一个像这样的表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)for 2nd表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

我需要修改查询,以便我可以减去前两行的值&#34; count(独占范围)&#34;对于从第2行开始的每一行...比如0-12(时间间隔)行我需要输出一个前两行差异的值。比如row(i)= count(i)-count(i -1)。

第一列给出5年(以月为单位)的时间间隔第二列计算否。专属范围内的员工如(0-6,0-12,0-18).. 6,12,18为否。几个月的第三栏计算没有。专属范围内的员工,如(0-6,6-12,12-18)

1 个答案:

答案 0 :(得分: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;