簡體   English   中英

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

[英]Minimum values between multiple columns ignoring zero and null value columns

我想從以下5列中創建一個名為Market_Min的新變量:

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

在這種情況下,答案應為100。

這是一個使用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

使用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函數添加到服務器。 您可以在這里下載

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM