sql营养价值条件和

ki1q1bka  于 2021-08-13  发布在  Java
关注(0)|答案(1)|浏览(250)

我有一张这样简单的table。

NutritionID | Value  
----------------------
1           |    10   
2           |    11  
3           |    12  
1           |    N      
1           |    Tr    
1           |    NULL

预期结果

NutritionID   | Value  
----------------------
 1            |   N   
 2            |   11  
 3            |   12

我需要得到每种营养素的总数。但是有一些规则可以决定最终的价值。例如,
n+n=n
n+tr=n
n+a值=n
tr+a值=值
tr+null=tr
null+0=0
心中的解决方案
为nutritionid创建光标
将运行和保存在变量中
在if/else语句中实现上述规则
问题
有没有更好的方法来获得有效的和与非光标的解决方案?也许是用case语句?
谢谢。

ekqde3dh

ekqde3dh1#

您不应该在同一列中混合字符串和数值-而且您的计算规则非常复杂。
我认为你可以用条件逻辑做你想做的事:

select
    nutritionID,
    case 
        when max(value = 'N' then 1 else 0 end) = 1 
            then 'N'
        when sum(try_cast(value as int)) is not null
            then cast(sum(try_cast(value as int)) as varchar(10))
        when max(value = 'Tr' then 1 else 0 end) = 1 
            then 'Tr'
    end
from mytable
group by nutritionID

基本上这是优先考虑 'N' ,然后是非- null 整数值之和,然后到 Tr ,和收益率 null 如果这些条件都不匹配。

相关问题