获得大于零的最小值

时间:2013-11-29 11:07:05

标签: sql-server tsql

我有下表:

column1   column2   column3
   3         2         0
   5         9         2
   1         4         6

当我运行以下代码时:

SELECT
  id_function = @param,
  MIN(t1.column1) AS c1min, 
  MAX(t1.column2) AS c2max,
  MIN(t1.column3) AS c3min
FROM
  table1 (NOLOCK) AS t1
WHERE
  t1.id = @param

我明白了:

c1min   c2max   c3min
  1       9       0

我的问题是c3min必须是大于零的最小值。 我需要的结果应该是:

c1min   c2max   c3min
  1       9       2

没有使用subselect有没有办法做到这一点? 任何帮助将不胜感激。

谢谢!

3 个答案:

答案 0 :(得分:13)

我建议使用nullif(),因此您的查询将是

SELECT id_function = @param,
   MIN(t1.column1) AS c1min, 
   MAX(t1.column2) AS c2max,
   MIN(NULLIF(t1.column3,0) AS c3min
FROM table1 (NOLOCK) AS t1
WHERE t1.id = @param

这样您就不会冒险改变结果,例如:如果第3列中的实际最小值为100,则上一个答案会影响您的结果,如果您的第3列中只有零,则上一个答案也会产生错误的结果

答案 1 :(得分:5)

您可以使用case0值设置为min()条件下的较高值

SELECT id_function = @param,
       MIN(t1.column1) AS c1min, 
       MAX(t1.column2) AS c2max,
       MIN(case when t1.column3 = 0 then 99 else t1.column3 end) AS c3min
FROM table1 (NOLOCK) AS t1
WHERE t1.id = @param

答案 2 :(得分:3)

有效。

(但我的回答是:Hedinn是最好的答案)。

SELECT  id_function = @param ,
    c1min = ( SELECT    MIN(t1Sub.column1)
              FROM      table1 (NOLOCK) AS t1Sub
              WHERE     t1Sub.id = @param
            ) ,
    c2max = ( SELECT    MAX(t2Sub.column2)
              FROM      table1 (NOLOCK) AS t2Sub
              WHERE     t2Sub.id = @param
            ) ,
    c3min = ( SELECT    MIN(t3Sub.column3)
              FROM      table1 (NOLOCK) AS t3Sub
              WHERE     ( t3Sub.id = @param )
                        AND ( t3Sub.column3 <> 0 )
            )
FROM    table1 (NOLOCK) AS t1
WHERE   ( t1.id = @param )