ID   State   blockID
1     0        1
2     1        1
3     1        2
4     0        2
5     2        1
6     2        3
7     2        3
8     2        3查询显示字段为blockID,bStatebState不是数据库中的字段bState的值是由相同的blockID的所有的state来决定的
如果State都是0,则为0
         都是1,则为1
         都是2,则为2
如果     部分为2,则为1结果应为
blockID    bState
1           1
2           1
3           2

解决方案 »

  1.   

    create table tb(ID int,  State int,  blockID int)
    insert tb
    select  1  ,   0        ,1
    union select 2     ,1        ,1
    union select 3     ,1        ,2
    union select 4     ,0        ,2
    union select 5     ,2        ,1
    union select 6     ,2        ,3
    union select 7     ,2        ,3
    union select 8     ,2        ,3
    ----这里面不知道,当State这个值只有0和1怎么处理,所以用的是NULLselect a.blockID,State=max(case when t.State=t.s/t.n then t.state when t.State<>t.s/t.n and t.State=2 then 1 else null end)
    from tb a inner join (select blockID ,State=max(State),n=count(1),s=sum(State) from tb group by blockID) t on a.blockID=t.blockID
    group by a.blockIDdrop table tb
      

  2.   

    declare @a table(ID int,State int, blockID int)
    insert @a select 1,0,1
    union all select 2,1,1
    union all select 3,1,2
    union all select 4,0,2
    union all select 5,2,1
    union all select 6,2,3
    union all select 7,2,3
    union all select 8,2,3
    select blockid,stated=case when sum(state)=0 then 0
                when sum(state)/count(1)=1 then 1
                when sum(state)/count(1)=2 then 2
              else 1 endfrom @a 
    group by blockid
    /*
    blockid     stated      
    ----------- ----------- 
    1           1
    2           1
    3           2(所影响的行数为 3 行)
    */
      

  3.   

    create table tb(State int,  blockID int)
    insert into tb values(0,        1)
    insert into tb values(1,        1)
    insert into tb values(1,        2)
    insert into tb values(0,        2)
    insert into tb values(2,        1)
    insert into tb values(2,        3)
    insert into tb values(2,        3)
    insert into tb values(2,        3)select blockID, State bstate from tb where blockid not in
    (
      select blockid from
      (
        select distinct blockID,bState = 1 from tb where state = 2 and blockID in (select blockID from tb where state = 1) 
        union all
        select distinct blockID,bState = 2 from tb where state = 2 and blockID not in (select blockID from tb where state = 1) 
      ) t1

    union all
    select distinct blockID,bState = 1 from tb where state = 2 and blockID in (select blockID from tb where state = 1) 
    union all
    select distinct blockID,bState = 2 from tb where state = 2 and blockID not in (select blockID from tb where state = 1) 
    order by blockIDdrop table tb/*
    blockID     bstate      
    ----------- ----------- 
    1           1
    2           1
    2           0
    3           2(所影响的行数为 4 行)
    */
      

  4.   

    sum(state)/count(1)=1  这个是什么意思??