各位达人,你们好,请帮小弟看一下这个查询能否实现我有一个表AppTable,里面有三列counts,appname,state
state是bit型,只能为true或者false情况1:
有如下数据:
counts   appname  state
3 应用1 1
1 应用2 0
2 应用2 1
3 应用3 1
我想查询出如下结果
3 应用1 1
2 应用2 1      //(counts是state为1的那行数据)
3 应用3 1情况2:
有如下数据:
counts   appname  state
3 应用1 1
1 应用2 0
3 应用3 1
我想查询出如下结果
3 应用1 1
1 应用2 0    //(counts是state为0的那行数据)
3 应用3 1意思就是,当appname相同时,如果有state为1的数据,查出state为1的那一行就可以,如果没有,就查出state为0的那条数据。注: 表中的数据同一appname的数据最多只能有两行,不会出现多余两行的数据
counts   appname  state
3 应用1 1
1 应用2 0
1 应用2 0
3 应用3 1这样的数据不会出现,所以不用担心这种情况。希望能有一个sql便能实现,不知道能不能行。

解决方案 »

  1.   

    --1.
    select * from AppTable where state=1--2.
    select * from AppTable a where not exists(select 1 from AppTable where appname =a.appname  and state>a.state)
      

  2.   

    哦,忘了说了,那个counts是我查询出来的count(state), 如果直接用max(state),不group by state是不行的,即
    select counts, appname, max(convert(int,state))
    from
    apptable
    group by counts,appname是不行的,
    因为我不group by state,那结果出来的count(state)是不对的
      

  3.   

    试试看select * from AppTable m where m.state=1 
    or exists(select 1 from AppTable t where t.counts=m.counts and t.state<>1)
      

  4.   

    select counts,appname,state from (
    select *,rn=row_number() over(partition by appname order by state desc)  from #test1
    ) a
    where rn=1
      

  5.   


    直接用 appname 分组以  state 倒叙 就可以了。
      

  6.   


    你这个sql能把state有0和1的时候都查询出来
    m.state=1 是为1的时候查询出来,
    exists(select 1 from AppTable t where t.counts=m.counts and t.state<>1)
    就是当有state为0的时候查询出来,而两个又是or关系,所以不管用,我试了的
    ,只不过还是谢谢
      

  7.   

    create table #test1(counts int,appname nvarchar(10),state bit)
    insert #test1 select 3 ,'应用1', 1
    insert #test1 select 1 ,'应用2', 0
    insert #test1 select 2 ,'应用2', 1
    insert #test1 select 3 ,'应用3', 1
    insert #test1 select 4 ,'应用4', 0--1.
    select counts,appname,state from (
    select *,rn=row_number() over(partition by appname order by state desc)  from #test1
    ) a
    where rn=1
    --2.
    select counts,appname,state from (
    select *,sum(cast(state as int)) over(partition by appname) as sum_state from #test1 
    ) a
    where state=sum_state--3.
    select * from #test1 a where state=(select sum(cast(state as int))  from #test1 where a.appname=appname)counts      appname    state
    ----------- ---------- -----
    3           应用1        1
    2           应用2        1
    3           应用3        1
    4           应用4        0(4 行受影响)
      

  8.   

    这样就差不多了select * from AppTable m where m.state=1 
    or (m.state=0 and not exists(select 1 from AppTable t where t.counts=m.counts and t.state=1))
      

  9.   

    select * from (
      select counts ,appname,state ,rownum=row_number()over (PARTITION by appname order by state desc)
      from AppTable
      ) as a 
      where rownum =1