sql根据条件选择min或max

时间:2015-08-04 16:54:05

标签: sql-server sql-server-2012

大家好我正试图找到一种方法,根据这些条件从一系列数据中选择最小值或最大值:

  • 如果setuptime和processtime cols都为0,则选择MIN(oprNum) (操作还没有开始,所以得到第一个oprnum)
  • 如果setuptime和process time不为0,则获取max oprnum(活动操作)。

根据其中任何一个我想要一行...请参阅附加的数据示例。谢谢!这是一个更大的查询的一部分,所以我需要每个prodid 1输出行...

+------------+--------+---------+--------------------+--------------------+
| 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 |
+------------+--------+---------+--------------------+--------------------+

2 个答案:

答案 0 :(得分:4)

根据上次评论更新了查询

  

如果最大记录有0次,我想选择最后一条记录   有一个设置时间或处理时间。如果我把这一行添加到你的小提琴   (' 12M0003381',80,12,0.00,0.00)当我想要最后一个时,我得到这一行   具有设置时间或处理时间

此查询使用的

逻辑仅用于计算其他列weighted_value。在外部查询中,我们使用min over value和max over weighted value,就像之前一样。

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

更新了小提琴链接:http://sqlfiddle.com/#!6/b7ecb/20

  

请尝试此查询

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

答案 1 :(得分:2)

一种方式:

SELECT 
    ProdId, 
    CASE WHEN SUM(SetupTime) + SUM(ProcessTime) = 0 THEN MIN(oprNum) ELSE MAX(oprNum) END 
FROM T
GROUP BY ProdId