select 人名,avg(数据1),avg(数据2),max(数据1),min(数据2)
from 表 group by 人名
这样可以查出,除 数据1时间 和 数据2时间 外的字段,你这连个测试数据都没有,根本就没办法分析你的问题,你既然 取了max(数据1),但又要查询 数据1时间,那你这个 数据1时间 到底想要查的是那个数据1 对应的时间。
select a.*
, max_data1, data1_time
, min_data2, data2_time
from (
select
username,
avg(data1) as avg_data1,
avg(data2) as avg_data2
from tb_table a
group by username
) as a
join (
select
username,
data1 as max_data1,
min(data1_time) as data1_time
from tb_table b
where 1=1
and not exists (select 1 from tb_table b0
where b0.username = b.username
and b0.data1 > b.data1)
group by username, data1
) as a1 on a1.username = a.username
select
username,
data2 as min_data2,
min(data2_time) as data2_time
from tb_table b
where 1=1
and not exists (select 1 from tb_table b0
where b0.username = b.username
and b0.data2 < b.data2)
group by username, data2
) as a2 on a2.username = a.username
ORACLE 可以直接函数取
greatest(repdate,repcreatedate,RepAuditTime,printime)
mssqlserver可能先列转行求分组最大,没有测试环境,忘记了