如何在排除某个值的同时获取一组列中的最小值?

时间:2014-11-18 06:16:19

标签: sql sql-server

我一直在尝试查询以选择一行中的最小值,但也排除某个值(-998)。

表格如下:

col1        col2         col3
----------------------------------
1            1          -998
2           -998        2
3            2          1
-998         1          3

所以在第一行中,最小值为1;在第二行,它将是2;在第三行,它将再次为1。

我尝试使用case语句并在每个条件中排除-998,但由于某种原因它仍然抓住-998。

SELECT  
    CASE
        WHERE (col1 <= col2 and col1 <= col3) and col1 != -998 THEN col1
        WHERE (col2 <= col1 and col2 <= col3) and col2 != -998 THEN col2
        WHERE (col3 <= col1 and col3 <= col2) and col3 != -998 THEN col3
    END AS [MIN_VAL]
FROM myTable

如果有人能指出我正确的方向,那就太棒了。

3 个答案:

答案 0 :(得分:5)

使用table value constructor取消列值,并从中排除值。

SQL Fiddle

MS SQL Server 2012架构设置

create table YourTable
(
  col1 int,
  col2 int,
  col3 int
);


insert into YourTable values
(1    ,        1   ,       -998),
(2    ,       -998 ,       2   ),
(3    ,        2   ,       1   ),
(-998 ,        1   ,       3   );

查询1

select (
       select min(R.Value)
       from (values(T.col1),
                   (T.col2), 
                   (T.col3)) as R(Value)
       where R.Value <> -998
       ) as min_val
from YourTable as T;

<强> Results

| MIN_VAL |
|---------|
|       1 |
|       2 |
|       1 |
|       1 |

答案 1 :(得分:0)

这个怎么样:

use tempdb

create table myTable(
    col1 int,
    col2 int,
    col3 int
)
insert into myTable values
(1, 1, -998),
(2, -998, 2),
(3, 2, 1),
(-998, 1, 3)

;with cte as(
    select
        rn = row_number() over(order by (select null)),
        col = col1
    from myTable
    union all
    select
        rn = row_number() over(order by (select null)),
        col = col2
    from myTable
    union all
    select
        rn = row_number() over(order by (select null)),
        col = col3
    from myTable
)
select
    minimum = min(col) 
from cte
where col <> - 998
group by rn

drop table mytable

答案 2 :(得分:0)

SELECT
     CASE
         WHEN (col1 <= col2 or col2 = -998)
              and (col1 <= col3 or col3 = -998)
              and col1 != -998 
         THEN col1
         WHEN (col2 <= col1 or col1 = -998)
              and (col2 <= col3 or col3 = -998)
              and col2 != -998 
         THEN col2
         WHEN (col3 <= col1 or col1 = -998)
              and (col3 <= col2 or col2 = -998)
              and col3 != -998 
         THEN col3
     END AS [MIN_VAL]
FROM myTable;