sql select min or max based on condition

无人久伴 提交于 2019-12-05 14:26:34

updated query: based on last comment

if the max record has 0 times, i want to select the last record that has a setuptime or process time. If I add this row to your fiddle ('12M0003381',80,12,0.00,0.00) I get this row when i want the last one with a setuptime or process time

logic used by this query is to simply calculate an additional column weighted_value. In outer query we use min over value and max over weighted value like before.

select 
  t.prodId,
  case when MAX(t.setuptime+ t.processtime)>0 then MAX(t.weighted_value) else MIN(t._value) end as value
from (
    select 
         prodID,
         oprnum as _value,
         setuptime,
         processtime,
         case 
           when setuptime+processtime>0 
           then oprnum 
           else NULL 
           end as weighted_value from tbl
    ) t
group by t.prodID

updated fiddle link: http://sqlfiddle.com/#!6/b7ecb/20

please try this query

select t1.ProdId, case when exists(
select 1 from tbl  t2 where t2.setuptime >0 or t2.Processtime>0 and t2.prodId=t1.prodId
)  then MAX(t1.oprNum) ELSE MIN(t1.oprNum) END
from tbl t1
group by ProdId

sql fiddle link http://sqlfiddle.com/#!6/c52e22/1

One way:

SELECT 
    ProdId, 
    CASE WHEN SUM(SetupTime) + SUM(ProcessTime) = 0 THEN MIN(oprNum) ELSE MAX(oprNum) END 
FROM T
GROUP BY ProdId
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!