id date a b a_time b_time
1 0100001643 2009-03-23 25.05 19.45 03月23日 14:58 03月23日 14:58
2 0100001645 2009-03-23 21.0 146.7 03月0日 0:0 03月23日 18:50
3 0100001646 2009-03-23 83.9 141.9 03月23日 18:39 03月23日 18:31
4 0100001643 2009-03-24 125.05 9.45 103月23日 14:58 203月23日 14:58
5 0100001645 2009-03-24 121.0 46.7 103月0日 0:0 203月23日 18:50
6 0100001646 2009-03-24 183.9 41.9 103月23日 18:39 203月23日 18:31
这样一个表,其中三个id,每个id对应两个日期,我现在想得到这两个日期内每个id的最大a值及最大a值出现时间,最大b值及最大b值出线的时间,结果是这样一个记录集,要怎么写啊,谢谢各位了? id a b a_time b_time
1 0100001643 125.05 19.45 103月23日 14:58 03月23日 14:58
2 0100001645 121.0 146.7 103月0日 0:0 03月23日 18:50
3 0100001646 183.9 141.9 103月23日 18:39 03月23日 18:31
1 0100001643 2009-03-23 25.05 19.45 03月23日 14:58 03月23日 14:58
2 0100001645 2009-03-23 21.0 146.7 03月0日 0:0 03月23日 18:50
3 0100001646 2009-03-23 83.9 141.9 03月23日 18:39 03月23日 18:31
4 0100001643 2009-03-24 125.05 9.45 103月23日 14:58 203月23日 14:58
5 0100001645 2009-03-24 121.0 46.7 103月0日 0:0 203月23日 18:50
6 0100001646 2009-03-24 183.9 41.9 103月23日 18:39 203月23日 18:31
这样一个表,其中三个id,每个id对应两个日期,我现在想得到这两个日期内每个id的最大a值及最大a值出现时间,最大b值及最大b值出线的时间,结果是这样一个记录集,要怎么写啊,谢谢各位了? id a b a_time b_time
1 0100001643 125.05 19.45 103月23日 14:58 03月23日 14:58
2 0100001645 121.0 146.7 103月0日 0:0 03月23日 18:50
3 0100001646 183.9 141.9 103月23日 18:39 03月23日 18:31
http://topic.csdn.net/t/20050512/10/4000561.html
from t
(select id,max(a) a from t group by id) t2
where t.id = t2.id and t.a = t2.a) ta,
(select id,b,b_time
from t
(select id,max(b) b from t group by id) t2
where t.id = t2.id and t.b = t2.b) tb
where ta.id = tb.id
这边假设你的表名为table1
select t1.id, t1.a, t2.b, t1.a_time, t2.b_time
from
(select id, max(a) a, a_time from table1 group by id) t1,
(select id, max(b) b, b_time from table1 group by id) t2
where t1.id = t2.id;
insert into test values(2, 2.5, 11, '20090201', '20090202');
insert into test values(3, 3.5, 10, '20090301', '20090302');
insert into test values(1, 3.5, 10, '20090401', '20090402');
insert into test values(2, 2.5, 11, '20090501', '20090502');
insert into test values(3, 1.5, 12, '20090601', '20090602');select id, max(a) a, max(a_time) a_time, max(b) b, max(b_time) b_time
from (
select id, a, a_time, row_number() over(partition by id order by a desc) rn_a, 0.0 b, '' b_time, 0 rn_b
from test
union all
select id, 0.0 a, '' a_time, 0 rn_a, b, b_time, row_number() over(partition by id order by b desc) rn_b
from test) t
where rn_a = 1 or rn_b = 1
group by id;