【问题标题】:How to show values in Col3 where Col1 values are true and for false values in Col1 show NULL in Col3 only如何在 Col3 中显示 Col1 值为 true 的值,而 Col1 中的 false 值仅在 Col3 中显示 NULL
【发布时间】:2021-12-07 15:19:43
【问题描述】:
SELECT Col1, Col2, Col3
FROM Table 

结果集:(样本表)

 Col1        Col2        col3
----------- ---------- -----------
Value       Value      Value
Value       Value      Value         
Value       Value      Value         
Value       Value      Value         
Value       Value      Value 

使用 NULL/空值显示 Col3(如果需要,假设 Col3 支持 NULL)除了 col1 条件为 true 的行(=values)保持值打开所有行的 Col2。

条件如( WHERE Col > 2| WHERE chareindex( 'x' , Col1 )等)

表格最终结果:(此处的条件适用于第 2 行和第 5 行)

  Col1        Col2        col3
----------- ---------- -----------
1 Value       Value      NULL
2 Value       Value      Value         
3 Value       Value      NULL         
4 Value       Value      NULL         
5 Value       Value      Value 

问题的更多表达方式:

SELECT EmployeeID, Firstname, Lastname,
From Employees 

结果集:

EmployeeID  FirstName  LastName
----------- ---------- --------------------
1           Nancy      Davolio
2           Andrew     Fuller
3           Janet      Leverling
4           Margaret   Peacock
5           Steven     Buchanan
6           Michael    Suyama
7           Robert     King

让我们说在上面的代码中有一个employeeID 和employeeID 3 和6 符合该条件的条件

我希望实现:

EmployeeID  FirstName  LastName
----------- ---------- --------------------
1           Nancy      NULL
2           Andrew     NULL
3           Janet      Leverling
4           Margaret   NULL
5           Steven     NULL
6           Michael    Suyama
7           Robert     NULL

应采用什么条件以及如何实现此结果集

  • 您可以完全更改“基本代码”
  • 您不知道“姓氏”col(或 col3)上的值
  • 您必须为错误条件值保留所有行和列值
  • 桌子很大

另一种提问方式:(根据问题的第一段)

对于 col1 中的值对某个条件/s 为真的行,显示 Col3 中的值,如果不显示 NULL/空,并保留所有行的 col2 值。

【问题讨论】:

  • 正确的样本数据和预期输出为 CREATE TABLE INSERT 将有很大帮助
  • 感谢您轻描淡写地采取行动并指出此处的不足

标签: sql-server tsql ssms


【解决方案1】:

我不确定是否完全了解您想要做什么,但是SELECT CASE WHEN 可以解决您的问题吗?

这是一个例子:

SELECT
    Col1, 
    Col2,
    CASE WHEN (Condition) THEN NULL ELSE Col3 END AS Col3
FROM Table 

它会返回这个输出:

 Col1        Col2        col3
----------- ---------- -----------
5           Value      Value
21          Value      NULL         
7           Value      Value         
8           Value      Value         
40          Value      NULL 

使用这种方式,你有条件地从列中选择数据或NULL

编辑:关于case...when的解释,你可以在这里找到解释和例子: https://www.w3schools.com/sql/sql_case.asp

【讨论】:

  • 已编辑:虽然我不理解代码结果与我要求的不同,但您需要保留 Col2 值,如“表格最终结果”中所示。
  • 所以只需选择 col1, col2, [case when] as col3
  • 只需重写您的答案和表格并标记为解决方案,也使用 (condition) 而不是 >20 作为一般条件,感谢您抽出宝贵时间阅读问题。
  • 这已经完成了,感谢您的反馈,我很感激
【解决方案2】:

试试这个:

Select col1, col2, 
Case When col1 (condition) Then col3 Else null End As col3 
From Table

【讨论】:

  • 只需编辑col1 (condition) then col3 就完美了。
  • *这确实是答案,但我不明白@Acuao 的答案,因为我不熟悉“case when statement”
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-06-15
相关资源
最近更新 更多