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

再来一个子查询。麻烦大家了。
字段A 字段B 字段C
A 结束 3
A 开始 2
A 开始 1
B 结束 7
B 开始 6
B 开始 5
B 开始 4
B 开始 3
B 开始 2
B 开始 1
C 开始 2
C 开始 1
D 开始 3
D 开始 2
D 开始 1

字段B是字段A的装填,需要把不含结束的记录集提取出来,并且只去最大的那个,所以,最终结果就是:
C 开始 2
D 开始 3
这样一个查询怎么写呢?


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

--> 测试数据:[test]
if object_id('[test]') is not null drop table [test]
create table [test]([字段A] varchar(1),[字段B] varchar(4),[字段C] int)
insert [test]
select 'A','结束',3 union all
select 'A','开始',2 union all
select 'A','开始',1 union all
select 'B','结束',7 union all
select 'B','开始',6 union all
select 'B','开始',5 union all
select 'B','开始',4 union all
select 'B','开始',3 union all
select 'B','开始',2 union all
select 'B','开始',1 union all
select 'C','开始',2 union all
select 'C','开始',1 union all
select 'D','开始',3 union all
select 'D','开始',2 union all
select 'D','开始',1


select [字段A],[字段B],MAX([字段C]) as [字段C]
from test
where [字段A] not in(
select [字段A] from test where [字段B]='结束'
)
group by [字段A],[字段B]

/*

字段A    字段B    字段C
C    开始    2
D    开始    3*/