【问题标题】:SQL SELECT from one of two columns where column value is not equal to somethingSQL SELECT 从列值不等于某物的两列之一
【发布时间】:2018-05-12 17:38:47
【问题描述】:

如果我有一个包含两列的表,并且其中一个列的值是已知的,有没有办法选择不等于已知值的值并将其转换为另一个列名?

例如

columna       columnb
1             5
3             1
4             1
1             7

我想在上表的两列中查询所有不等于 1 的值,并在名为 column(或类似名称)的单列中返回列表,即结果表应为:

column
3
4
5
7

【问题讨论】:

  • 已知值是多少?你想要什么结果?
  • 嗨 Gordon,我想查询上面的表中所有不等于 1 的值,所以如果 columna 或 columnb 中的任何值不是一个,我希望它返回,在一个表中单列

标签: sql sql-server


【解决方案1】:

我想你只是想要:

select distinct col
from t cross join
     (values (columna), (columnb)) v(col)
where col <> 1;

这将捕获两列都不是“1”的情况。

如果您的意图类似于聊天中的“其他谈话者”,那么:

select t.*, (case when columna <> 1 then columna else columnb end) as col
from t
where 1 in (columna, columnb);

【讨论】:

    【解决方案2】:

    您正在寻找:

    您的查询:

    SELECT 
           columnb as [column]  --here the alias
    FROM 
           yourTable
    WHERE 
           columnb <> 1 or columnea <>1   --here the where clause
    

    注意:您可以在where 子句中使用andor 运算符。

    引用t-sql select docs:

    列别名 是替换查询结果集中列名的替代名称。例如,可以为名为数量的列指定别名,例如 Quantity、Quantity to Date 或 Qty。 别名也用于指定表达式结果的名称,例如:

    SELECT AVG(UnitPrice) AS [Average Price] FROM Sales.SalesOrderDetail;

    已编辑由于 OP cmets:

    要从两列中获取值,最简单的方法是UNION

    SELECT 
           columnb as [column]  --here the alias
    FROM 
           yourTable
    WHERE 
           columnb <> 1         --here the where clause
    UNION ALL
    SELECT 
           columna as [column]  --here the alias
    FROM 
           yourTable
    WHERE 
           columna <> 1         --here the where clause
    

    【讨论】:

    • 我需要它只返回一列
    • 好的,现在一栏。
    • 抱歉 dani 我可能不清楚 - 我想要的值可能在 columna 或 columnb 中,我需要该值,无论它是否位于任一列中。这个答案只检查 columnb
    • 只返回来自 columnb 的值
    • 好的,你需要在一列中有两个值吗?这在 SQL 上是不可能的。可能是串联的?
    猜你喜欢
    • 2011-12-30
    • 1970-01-01
    • 2020-12-29
    • 1970-01-01
    • 2022-10-06
    • 2023-03-27
    • 2014-04-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多