Sql 忽略零值列和空值列的多列之间的最小值
我想从以下5列中创建一个名为Sql 忽略零值列和空值列的多列之间的最小值,sql,minimum,Sql,Minimum,我想从以下5列中创建一个名为Market\u 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 fro
Market\u 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
根据评论进行编辑 如果您需要每行的最小值,您可以在子查询中引入
行号
,并按它分组:
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\u分割使用不同的方法
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函数添加到服务器。您可以下载哪些您关心使用哪种语言吗?你能使用Excel或LibreOffice之类的电子表格软件吗?对不起,忘了提。。。为什么100
是正确答案?你在寻找最小的非空正数吗?目前我正在使用以下代码:CASE WHEN Col1>0 then(CASE WHEN isnull(col1999999)是的..我在寻找非空和非零的最小值作为答案..啊!它起作用了..但它给了我一个最小值..我实际上有1000行和5列,我想为每行获得一个最小值..为混淆道歉..请帮助我基本上想在数据中添加一个新列,显示整个数据库中每行的最小值5.columns@user3637879--您需要一个行号来分组。如果您有一个id,那最好。如果没有,您可以这样创建一个:例如,第1行:第1列为0,第2列为100,第3列为200,第4列为150,第5列为空,第2行:第1列为400,第2列为120,第3列为200,第4列为150,第5列为空。我想用第1行的值将第6列添加为Market\u Minas 100和第2行as 120非常好的答案。如果您有要分组的行标识符,则可以使用上面的方法获得每行的最小值。即RecordId、min(ComineCol)…stuff…group by RecordId