我想从以下5列创建一个名为Market_Min
的新变量,其中:
Col 1 is 0
Col 2 is 100
Col 3 is 200
Col 4 is 150
Col 5 is NULL
在这种情况下,答案应为100。
答案 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