忽略零值和空值列的多列之间的最小值

时间:2014-05-14 18:06:20

标签: sql minimum

我想从以下5列创建一个名为Market_Min的新变量,其中:

Col 1 is 0
Col 2 is 100
Col 3 is 200
Col 4 is 150
Col 5 is NULL

在这种情况下,答案应为100。

2 个答案:

答案 0 :(得分:1)

以下是使用union all获取整个表格中最小值的一个选项:

select min(combinedcol)
from (
    select col1 combinedcol from yourtable union all
    select col2 from yourtable union all
    select col3 from yourtable union all
    select col4 from yourtable union all
    select col5 from yourtable
) t
where coalesce(combinedcol,0) > 0

根据评论进行修改

如果您需要每行的最小值,则可以在子查询中引入row_number并在group by中引入它:

select rn, min(combinedcol)
from (
    select row_number() over (order by (select null)) rn, col1 combinedcol from yourtable union all
    select row_number() over (order by (select null)) rn, col2 from yourtable union all
    select row_number() over (order by (select null)) rn, col3 from yourtable union all
    select row_number() over (order by (select null)) rn, col4 from yourtable union all
    select row_number() over (order by (select null)) rn, col5 from yourtable
) t
where coalesce(combinedcol,0) > 0
group by rn

答案 1 :(得分:0)

使用fn_Split

使用不同的方法
DECLARE @Temp AS TABLE (col1 int, col2 int,  col3 int, col4 int , col5 int)

INSERT INTO @Temp
    (col1 , col2 ,  col3 , col4 , col5 )
VALUES
    ( 0, 200, 100, 150,NULL)
SELECT
    *
    ,
    (
    SELECT 
        MIN(Value) 
    FROM 
        dbo.fn_Split
        (
          CAST(ISNULL(NULLIF(col1,0),99999) AS VARCHAR(10)) +','
        + CAST(ISNULL(NULLIF(col2,0),99999) AS VARCHAR(10)) +','
        + CAST(ISNULL(NULLIF(col3,0),99999) AS VARCHAR(10)) +','
        + CAST(ISNULL(NULLIF(col4,0),99999) AS VARCHAR(10)) +','
        + CAST(ISNULL(NULLIF(col5,0),99999) AS VARCHAR(10))
        ,','
        )
    ) AS MinNonZeroNonNullValue
FROM
    @Temp

您需要将fn_Split功能添加到服务器。你可以下载Here