日期:2014-05-17  浏览次数:20577 次

求一语句,求最大值和其对应的时间
有表tab1,字段 [产品ID],[时间]、[值1],[值2],[值3],[值4],值5],.....
现在要求一段时间内每个[产品ID]下[值1]最大时的时间和最大值,该这么写语句,可以一步到位,且查询速度最快呢,
[时间]和[时间],[产品ID]分别有索引,
基本做法:
select [产品ID],max([值1])max_值1 into #temp_1 from tab1 
where group by [产品ID]

select a.[产品ID],a.[时间],[值1],[值2],[值3],[值4],值5],.....
from tab1 a,#temp_1 b where a.[产品ID]=b.[产品ID] and a.[值1]=b.max_值1
大家有没有更好的!





------解决方案--------------------
SQL code
 
select *
from tb t
where not exists (select 1 from tb where 产品=t.产品 and [值1]>t.[值1])

------解决方案--------------------
SQL code
 
with t as
(
select *,ROW_NUMBER() over(partition by 产品ID order by [值1] desc) as rn
from tb1
where ....
)
select * From t
where rn=1

------解决方案--------------------
select *
from tb t
where not exists (select 1 from tb where 产品=t.产品 and [值1]>t.[值1])
------解决方案--------------------
select *
from tb t
where not exists (select 1 from tb where 产品=t.产品 and [值1]>t.[值1])


------解决方案--------------------
用子查询吧,数据量不大的话,效率都差不多

SQL code
SELECT * 
FROM  tb t
WHERE  NOT EXISTS (SELECT 1
        FROM  tb
        WHERE  产品 = t.产品
            AND [值1] > t.[值1])