求SQL!
表A:
字段a 字段b 字段C
1001 1 0
1001 2 1
1001 3 0
1002 1 1
1002 2 0
1002 3 1
.....
1009 1 0
1009 2 0
1009 3 1
1009 4 1
要求找出如下结果:
字段a 字段b 字段C
1002 3 1
.....
1009 4 1
即要求按字段a每个取出一条记录,且这条记录的字段b为最大,同时只取出字段C为1的记录,如果为0的不要.
------解决方案--------------------select a.* from [表A] a
inner join
(select 字段a,max(字段b) as 字段b from [表A] group by 字段a) b
on a.字段a=b.字段a and a.字段b=b.字段b
where a.字段c=1
------解决方案--------------------哦我明白了
------解决方案-------------------- create table A(col1 int, col2 int, col3 int)
insert A select 1001, 1, 0
union all select 1001, 2, 1
union all select 1001, 3, 0
union all select 1002, 1, 1
union all select 1002, 2, 0
union all select 1002, 3, 1
union all select 1009, 1, 0
union all select 1009, 2, 0
union all select 1009, 3, 1
union all select 1009, 4, 1
select * from A as tmpA
where not exists(select 1 from A where col1=tmpA.col1 and col2> tmpA.col2)
and col3=1
--result
col1 col2 col3
----------- ----------- -----------
1002 3 1
1009 4 1
(2 row(s) affected)
------解决方案--------------------select * from ta as a
where col2=(select max(col2) from ta where col1=a.col1 and col3=a.col3 and col3=1)