【问题标题】:Is there a way to retrieve a table column name based on cell value?有没有办法根据单元格值检索表列名?
【发布时间】:2021-04-16 10:42:39
【问题描述】:

有没有办法根据 SQL Server 2016 中的单元格值检索列名?

下面是表结构

Col1  Col2  Col3  Col4
N     Y     N     Y

我需要 value = N 的列名,即输出应该是 Col1, Col3

【问题讨论】:

  • N'Col2'N'Col4' 的值是'Y' 而不是'N' 并且您想要具有'N' 值的列时,为什么要返回它们?
  • 再添加一些样本数据行,并指定预期的结果。
  • 更正了所需的输出
  • 所有值在哪里 =N ?还是至少有一个值 =N?

标签: sql sql-server


【解决方案1】:

我怀疑您正在寻找的是一个逗号分隔的列名列表,满足您对每一行的条件。如果我猜对了,我想你想要

select replace(rtrim(concat (nullif(case when col1='N' then 'col1 ' end, ''),
                             nullif(case when col2='N' then 'col2 ' end, ''),
                             nullif(case when col3='N' then 'col3 ' end, ''),
                             nullif(case when col4='N' then 'col4 ' end, ''))),' ',',')
from your_table;

注意如果所有 4 列都有空值,这将返回一个空字符串。

Demo

【讨论】:

  • 是的,我正在寻找逗号分隔的列名。但 concat_ws() 在 SQL server 2016 中无法识别
  • @shiva 现在试试。解决方案有点难看,但是如果您可以使用空格而不是逗号,那么您实际上可以摆脱替换。
  • 谢谢@Phil Coulson,我或多或少做了同样的事情来解决它。选择 case when col1='N' then 'col1' + ',' else '' end + case when col2='N' then 'col2'+',' else '' end + ........
  • @shiva 请注意,如果任何列为空,您的代码将返回空
【解决方案2】:

我更喜欢在这里使用VALUES 表结构来反透视数据:

SELECT V.ColName
FROM dbo.YourTable YT
     CROSS APPLY (VALUES(N'Col1',Col1),
                        (N'Col2',Col2),
                        (N'Col3',Col3),
                        (N'Col4',Col4))V(ColName,ColValue)
WHERE V.ColValue = 'N';

【讨论】:

    【解决方案3】:

    您需要在 SQL 中明确。像这样的:

    select 'Col1' as col from t where col1 = 'N' union all
    select 'Col2' as col from t where col2 = 'N' union all
    select 'Col3' as col from t where col3 = 'N' union all
    select 'Col4' as col from t where col4 = 'N';
    

    或者:

    select v.col
    from t cross apply
         (values ('col1', col1), ('col2', col2), ('col3', col3), ('col4', col4)
         ) v(col, val)
    where val = 'N';
    

    【讨论】:

      猜你喜欢
      • 2023-03-08
      • 2015-03-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-20
      相关资源
      最近更新 更多