gpt4 book ai didi

sql - 如何使用 unpivot 函数在其他列中查找最小值来忽略字符串值

转载 作者:行者123 更新时间:2023-12-04 22:12:51 24 4
gpt4 key购买 nike

我有一张看起来像这样的 table

enter image description here

目标是在 Limit 列(Limit1、Limit2、Limit3...等)中找到最小值。

为此,我使用了 UNPIVOT 函数。

但问题是有些值是空字符串。结果,最小值变为空字符串。

declare @TempTable2 table (ID int, limit1 varchar(50),limit2 varchar(50),limit3 varchar(50),limit4 varchar(50),limit5 varchar(50) )
insert into @TempTable2 values (1,'1000','1000','3000',NULL, NULL)
,(2,'2000','4000','3000','', NULL)

--select * from @TempTable2
Select ID,
min(Amount) as TheMin
from @TempTable2
unpivot (Amount for AmountCol in (Limit1,Limit2,Limit3,Limit4,Limit5)) as unpvt
group by ID

enter image description here

那么如何在使用 UNPIVOT 函数时忽略字符串值呢?

我希望我的结果是这样的:

ID  TheMin
1 1000
2 2000

我尝试使用 NULLIFUNPIVOT 不接受它。谢谢

最佳答案

另一个选项是 NullIf()

示例

Select  ID, 
min(nullif(Amount,'')) as TheMin
from @TempTable2
unpivot (Amount for AmountCol in (Limit1,Limit2,Limit3,Limit4,Limit5)) as unpvt
group by ID

返回

ID  TheMin
1 1000
2 2000

关于sql - 如何使用 unpivot 函数在其他列中查找最小值来忽略字符串值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53054577/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com