SQL Server 2008,如何计算更改的不同值

时间:2016-12-27 08:00:32

标签: sql sql-server

我的实体有2个答案y / n。

我需要计算更改答案的实体数量来自' n'到了'在stage1和stage2之间。

entity || answer || stage
    a  ||   y    ||  1
    a  ||   n    ||  2
    b  ||   y    ||  1
    b  ||   y    ||  2
    c  ||   n    ||  1
    c  ||   n    ||  1 
    d  ||   n    ||  1
    d  ||   y    ||  2  

我尝试了这个,但这不起作用(因为它会计算所有更改答案的实体)

select 
    entity, count(distinct answer)
from 
    myDB
where 
    stage between '1' and '2'
group by 
    entity, answer

但我不明白为什么这不起作用,结果出来了所有的

select 
    entity, 
    case 
       when stage = '1' and answer = 'n' and 
            stage = '2' and answer = 'y' then 1
       else 0 
    end as 'result'
from 
    myDB 
where 
    stage between '1' and '2'
group by 
    entity, stage, answer

4 个答案:

答案 0 :(得分:2)

select count(*) 
from myDB s2
where 
    s2.stage ='2' and s2.answer='y'
    and exists (select * from myDB s1 
                 where s1.entity=s2.entity 
                 and s1.stage ='1' and s1.answer='n'
               )

答案 1 :(得分:0)

 select     count(*) 

 from      (select      1 as x
            from        myDB 
            where       stage in (1,2)
            group by    entity
            having      min(case when stage = 1 then answer end) = 'n' 
                    and max(case when stage = 2 then answer end) = 'y'
            ) t

答案 2 :(得分:0)

select  count(*)
from    (select entity,stage,answer from myDB) t
            pivot (max(answer) for stage in([1],[2])) p
where   [1] = 'n' and [2] = 'y'

答案 3 :(得分:0)

select 
    count(*)
from 
    [myDb] as [s1] 
inner join 
    [myDb] as [s2] 
on 
        [s1].[entity]   =   [s2].[entity] 
    and [s1].[answer]   =   'n'
    and [s1].[stage]    =   1
    and [s2].[answer]   =   'y' 
    and [s2].[stage]    =   2;

但是,它仅适用于您提供的数据。 如果你有重复的恩赐,它就不起作用,因为在这种情况下,并不是不可能识别实体的唯一性。那你需要额外的数据。

a   y   1
a   n   2
b   y   1
b   y   2
c   n   1
c   n   2
d   n   1
d   y   2
d   n   1
d   y   2

让我们假设,相同的逻辑实体值一个接一个地存储。然后,您可以使用此查询来处理此问题:

declare @myDB TABLE
(
     [rec_id]   int         identity(1, 1)  
    ,[entity]   varchar(10)
    ,[answer]   varchar(10)
    ,[stage]    int
);


insert into @myDB
(   
     [entity]
    ,[answer]
    ,[stage]
)
select
     [entity]
    ,[answer]
    ,[stage]
from
    [myDB];


select 
     [s1].[entity]
    ,count([s1].[entity])
from 
    @myDB as [s1] 
inner join 
    @myDB as [s2] 
on 
        [s1].[entity]   =   [s2].[entity] 
    and [s1].[answer]   =   'n'
    and [s1].[stage]    =   1
    and [s2].[answer]   =   'y' 
    and [s2].[stage]    =   2
    and [s1].[rec_id]   =   [s2].[rec_id] - 1
group by
    [s1].[entity];