如果null值提前选择下一列

时间:2016-01-29 17:30:47

标签: sql sql-server

我只需要一个列

的表中的一个血压值

B/P | Sitting | Lying | Standing

通常情况下,有一般的血压,然后是每种姿势的血压。我基本上只需要其中一个值,重要性是从左到右。如果血压为空,则选择坐值,如果坐标值为空,则选择卧位值,如果卧位值为空,则选择常设值

我需要像

这样的东西
SELECT
    case when bloodpressure is null or bloodpressure = ''
        then case when sitting is null or sitting = ''
            then case when lying is null or lying = ''
                then case when standing is null or standing = ''
                    standing
                end
                lying
            end
            sitting
        end
    bloodpressure
    end
    as bloodpressure

4 个答案:

答案 0 :(得分:1)

试试这个

SELECT CASE
         WHEN bloodpressure IS NOT NULL
               AND bloodpressure <> '' THEN bloodpressure
         WHEN sitting IS NOT NULL
               AND sitting <> '' THEN sitting
         WHEN lying IS NOT NULL
               AND lying <> '' THEN lying
         WHEN standing IS NOT NULL
               AND standing <> '' THEN standing
       END AS bloodpressure 

IS NOT NULL AND standing <> ''可以替换为NULLIF(standing,'') IS NOT NULL

答案 1 :(得分:1)

这看起来像是:

SELECT 
    CASE 
        WHEN ISNULL(bloodpressure,'') <> '' THEN bloodpressure
        WHEN ISNULL(sitting,'') <> '' THEN sitting
        WHEN ISNULL(lying,'') <> '' THEN lying
        WHEN ISNULL(standing,'') <> '' THEN standing
    ELSE 
        '0' END AS bloodpressure

我还将ELSE条件添加为0,因为如果所有字段都为空,则必须收到0.如果不需要,则可以将其删除。

如果所有的enpty值都是NULL,那么您可以使用COALESCE

答案 2 :(得分:0)

如果值为null或有效,您可以尝试:

SELECT ISNULL(bloodpressure, ISNULL(sitting, ISNULL(lying, standing))) AS bloodpressure

或使用COALESCE(正如@Bogdan Bogdanov建议的那样)

SELECT COALESCE(bloodpressure, sitting, lying, standing) AS bloodpressure

答案 3 :(得分:0)

您也可以使用coalesce + nullif:

select coalesce (
  nullif(bloodpressure,''), 
  nullif(sitting,''), 
  nullif(lying,''), 
  standing)

此外,您不应该在列中存储空字符串,这只是糟糕的数据库设计。