当前位置: 代码迷 >> Sql Server >> 请问一个sql过滤取数据语句
  详细解决方案

请问一个sql过滤取数据语句

热度:54   发布时间:2016-04-27 14:11:17.0
请教一个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 caselect 1, 10, 0 union allselect 2, 10, 0 union allselect 3, 10, 1 union allselect 4, 10, 2 union allselect 5, 11, 0 union allselect 6, 12, 3 union allselect 7, 12, 3 union allselect 8, 13, 4select 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          05           11          06           12          38           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……
  相关解决方案