SQL简单加入,我很难过

时间:2010-07-30 18:38:10

标签: sql join

我有一个包含列的表:

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  

我从哪里开始?

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:2)

当您需要唯一的行时,为所需的所有数字(带有重复项)或UNION创建一个UNION ALL:

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

答案 2 :(得分: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