Hi all I'm trying to find a way to select min or max from a range of data based on these conditions:
Based on either of these I want ONE row... Please see attached example of data. Thanks! This is part of a much larger query so i need 1 output row per prodid...
+------------+--------+---------+--------------------+--------------------+
| ProdId | OprNum | Company | SetupTime | ProcessTime |
+------------+--------+---------+--------------------+--------------------+
| 12M0003381 | 10 | 12 | 1.3400000000000000 | 1.6100000000000000 |
+------------+--------+---------+--------------------+--------------------+
| 12M0003381 | 10 | 12 | 0.0000000000000000 | 0.0000000000000000 |
+------------+--------+---------+--------------------+--------------------+
| 12M0003381 | 15 | 12 | 1.0000000000000000 | 0.0000000000000000 |
+------------+--------+---------+--------------------+--------------------+
| 12M0003381 | 50 | 12 | 0.0000000000000000 | 0.0000000000000000 |
+------------+--------+---------+--------------------+--------------------+
| 12M0003381 | 60 | 12 | 0.0000000000000000 | 0.0000000000000000 |
+------------+--------+---------+--------------------+--------------------+
| 12M0003381 | 60 | 12 | 0.0000000000000000 | 0.0000000000000000 |
+------------+--------+---------+--------------------+--------------------+
| 12M0003381 | 70 | 12 | 0.0700000000000000 | 0.0400000000000000 |
+------------+--------+---------+--------------------+--------------------+
| 12M0003381 | 70 | 12 | 0.0000000000000000 | 0.0000000000000000 |
+------------+--------+---------+--------------------+--------------------+
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With