Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
172 views
in Technique[技术] by (71.8m points)

sql - Is there a way to retrieve a table column name based on cell value?

Is there a way to retrieve column name based on cell value in SQL Server 2016?

Below is the table structure

Col1  Col2  Col3  Col4
N     Y     N     Y

I need column names where value = N i.e output should be Col1, Col3


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You need to be explicit in the SQL. Something like this:

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';

Or:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...