2010-07-30 58 views
4

我有列的表格:SQL簡單的加入,我難倒

JOB_NUM, HM_PH, BUS_PH, CALL1ST 

job_num是唯一編號

而且HM_PHBUS_PHCALL1ST列10個電話號碼

因此,使用上面列的順序,樣本數據看起來像:

JOB_NUM, HM_PH,  BUS_PH,  CALL1ST 
------------------------------------ 
12345, 4025557848, 9165897588, 7518884455 
10101, 8887776655, 8667416895, 5558884446 

我想要生產的是2列。

JOB_NUM, PHONE 

凡job_num旁邊列出的每個電話號碼,如:

JOB_NUM PHONE 
--------------------- 
12345 4025557848 
12345 9165897588 
12345 7518884455 
10101 8887776655 
10101 8667416895 
10101 5558884446 

從哪裏開始?

+0

@OMG我很高興,我雙下降我的修訂權在你的頂部前檢查。 ;) – ahsteele 2010-07-30 18:45:01

+0

@ahsteele:無論如何都有修訂,你總是可以回滾;) – Tim 2010-07-30 19:26:10

回答

10

你需要一個UNION(如果你想刪除重複的行)或UNION ALL(如果你想保留重複行):

SELECT JOB_NUM, HM_PH AS PHONE FROM yourtable 
UNION 
SELECT JOB_NUM, BUS_PH FROM yourtable 
UNION 
SELECT JOB_NUM, CALL1ST FROM yourtable 
ORDER BY JOB_NUM 
+2

+1 - 添加一個「ORDER BY JOB_NUM」到最後。 – JNK 2010-07-30 18:41:40

+6

@CodingIsAwesome:請注意'UNION'會刪除重複項; '聯盟所有'不會,而且會更快。 – 2010-07-30 18:44:19

+0

@OMG小馬:+1好點。添加。 @JNK:修正了,謝謝。 – 2010-07-30 18:53:34

2

做一個UNION ALL你所需要的所有號碼(含重複)或UNION當你需要的唯一行:

select JOB_NUM,HM_PH AS PHONE 
from YourTableName 
union all 
select JOB_NUM,BUS_PH AS PHONE 
from YourTableName 
union all 
select JOB_NUM,CALL1ST_PH AS PHONE 
from YourTableName 
0
create table yourtable 
(
    id int, 
    HM_PH nvarchar(10), 
    BUS_PH nvarchar(10), 
    CALL1ST nvarchar(10) 
) 


insert into yourtable 
select 12345, 4025557848, 9165897588, 7518884455 
union 
select 10101, 8887776655, 8667416895, 5558884446 



select * from yourtable 

select ID,p.Phone 
from temptemp 
unpivot(Phone for phoneCol in (HM_PH,BUS_PH,CALL1ST)) p 
order by id 

drop table yourtable