日期:2014-05-18  浏览次数:20530 次

请教一个sql过滤取数据语句
例如有一个表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



现在的做法是先把全部数据查出来,然后用程序循环过滤,但是这样的效率很低



------解决方案--------------------
SQL code

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=1

ID          A           B
----------- ----------- -----------
1           10          0
5           11          0
6           12          3
8           13          4

------解决方案--------------------
SQL code
select * from tb t where id=(select min(id) from tb where a=t.a)

------解决方案--------------------
探讨

SQL code

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
se……