【问题标题】:How to select value from second column if first column is blank/null in SQL (MS SQL)?如果 SQL (MS SQL) 中的第一列为空白/空,如何从第二列中选择值?
【发布时间】:2015-05-30 00:22:47
【问题描述】:

有人可以帮我构建一个 SQL 查询,如果 column1 为空/空白,我应该从 column2 获取值,如果 column2 也是空白/null,我应该从 column3 获取值。

下面是我正在使用的表格

Price1   Price2   Price3

120

          140

                 160

我正在寻找的输出是

Price

120

140

160

我已经试过了

select Price1 as Price
from A
WHERE PRICE1 IS NOT NULL
UNION
SELECT PRICE2 as Price
from A
where PRICE1 is null
UNION 
select PRICE3 as id
from A
where PRICE2 is null

select COALESCE (PRICE1,PRICE2,PRICE3) from A

select ISNULL(PRICE1,ISNULL(PRICE2,PRICE3)) from A

select 
case when PRICE1 IS not null then PRICE1 when PRICE1 IS null then PRICE2 WHEN PRICE2 IS NULL then PRICE3 end PRICE id from A

以上语法都没有得到我正在寻找的数据。请帮忙

【问题讨论】:

  • 那些是空值还是空白。如果它们是空值,则合并应该起作用……如果它们是空白,则不会。尝试更改 case 语句以将“IS NOT NULL”替换为“ ''”,如果这样解决了问题,那么您将得到空白而不是空值。
  • 任何答案有用吗?

标签: sql sql-server


【解决方案1】:

像这样使用COALESCE

SELECT COALESCE(Price1, Price2, Price3) FROM A;

但是,如果条目是空白而不是 NULL,这将不起作用。

【讨论】:

    【解决方案2】:

    如果您的字段可能为空或空白,您应该检查以下内容:

    select Price1 as Price
    from A
    WHERE PRICE1 IS NOT NULL AND PRICE1 != ''
    UNION
    SELECT PRICE2 as Price
    from A
    where PRICE1 is null OR PRICE1 = ''
    UNION 
    select PRICE3 as id
    from A
    where (PRICE1 is null OR PRICE1 = '') AND (PRICE2 is null OR PRICE2 = '')
    

    【讨论】:

      【解决方案3】:

      如果你认为你有空字符串,你可以试试:

      select 
        case when coalesce(PRICE1, '') <> '' then PRICE1 
             when coalesce(PRICE2, '') <> '' then PRICE2 
             when coalesce(PRICE3, '') <> '' then PRICE3 
        end AS PRICE 
      FROM A
      

      【讨论】:

      • 感谢 Forgues,这回答了我的担忧。
      【解决方案4】:

      简单,如果第一列为空,则查看第二列,如果为空,则查看第三列。

      select isnull(PRICE1,isnull(PRICE2,PRICE3)) as Price from A
      

      【讨论】:

        猜你喜欢
        • 2017-05-01
        • 2017-04-16
        • 1970-01-01
        • 2023-03-03
        • 1970-01-01
        • 2022-01-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多