例如有一个表T,包含字段ID,A,B查数据要求:对于有相同A的数据,如果有B为0的数据,则只取1条;如果没有B为0则去掉B相同数据ID  A     B
1   10    0
2   10    0
3   10    1
4   10    2
5   11    0
6   12    3
7   12    3
8   13    4查询出来的结果为
ID  A     B
1   10    0
5   11    0
6   12    3
8   13    4现在的做法是先把全部数据查出来,然后用程序循环过滤,但是这样的效率很低

解决方案 »

  1.   


    create table ca
    (ID int, A  int, B int)insert into ca
    select 1, 10, 0 union all
    select 2, 10, 0 union all
    select 3, 10, 1 union all
    select 4, 10, 2 union all
    select 5, 11, 0 union all
    select 6, 12, 3 union all
    select 7, 12, 3 union all
    select 8, 13, 4
    select t.ID, t.A, t.B from
    (select row_number() over(partition by A order by B) rn, 
    * from ca) t where t.rn=1ID          A           B
    ----------- ----------- -----------
    1           10          0
    5           11          0
    6           12          3
    8           13          4
      

  2.   

    select * from tb t where id=(select min(id) from tb where a=t.a)
      

  3.   


    row_number()over()可以对数据进行分区排序,楼主的问题使用这个方法解决比较简单点