2013-03-12 50 views
1

我有這個表:SQL查詢來獲取兩列的結果集僅

id fName lName Address PostCode ContactNumber 
----------------------------------------------------- 
1 Tom  Daley London  EC1 4EQ 075825485665 
2 Jessica Ennis Sheffield SF2 3ER 075668956665 
3 Joe  Bloggs Glasgow G3 2AZ 075659565666 

我想查詢給我的結果是這樣的:

id | label 
1 | Tom 
1 | Daley 
1 | London 
1 | EC1 4EQ 
1 | 075825485665 
2 | Jessica 
2 | Ennis 
2 | Sheffied 

等等等等。

任何建議請就如何做到這一點。

回答

3

可以使用UNPIVOT功能轉列到行:

select id, value 
from yourtable 
unpivot 
(
    value 
    for col in ([fName], [lName], [Address], [PostCode], [ContactNumber]) 
) unpiv 

SQL Fiddle with Demo

unpivot將要求所有列上的數據類型相同。所以,你可能需要用類似上述不同的數據類型進行任何列cast/convert

select id, value 
from 
(
    select id, [fName], [lName], [Address], [PostCode], 
    cast([ContactNumber] as varchar(15)) [ContactNumber] 
    from yourtable 
) src 
unpivot 
(
    value 
    for col in ([fName], [lName], [Address], [PostCode], [ContactNumber]) 
) unpiv; 

SQL Fiddle with Demo

在SQL Server 2008開始,這也可以使用CROSS APPLYVALUES寫着:

select t.id, 
    c.value 
from yourtable t 
cross apply 
(
    values(fName), 
    (lName), 
    (Address), 
    (PostCode), 
    (cast(ContactNumber as varchar(15))) 
) c (value) 

SQL Fiddle with Demo

+0

非常感謝演示以及。它工作得很好。 – nasaa 2013-03-12 10:54:26

+0

@nasaa不客氣,總是樂於幫忙! :) – Taryn 2013-03-12 10:58:49

0

怎麼是這樣的:

SELECT 
id, fName as label 
FROM 
table 

UNION ALL 

SELECT 
id, lName 
FROM 
table 

UNION ALL 

SELECT 
id, Address 
FROM 
table 

...etc