2017-10-12 126 views
1

表1獲得列名: -如何選擇查詢基於列的值在SQL Server

ID NAME ADDRESS 
1 TEST1 qwr 
2 TEST2 sdf 

我希望根據ID列的值在選擇查詢獲取列名

EX: - 在選擇查詢

如果ID = 1我想在選擇查詢 「名稱」列在ID = 2我想「地址」欄

select name from table (when id=1) 
select address from table(when id=2) 

我希望我清楚地表達了我的疑問。

回答

0

您可以使用子查詢得到兩個結果:

select (select name from table where id = 1) as name, 
     (select address from table where id = 2) as address; 
2

這個查詢將返回一列結果,並多行:

SELECT CASE WHEN id = 1 THEN name WHEN id = 2 THEN address END AS result 
    FROM table;