Sql select union同一个表

时间:2016-06-21 22:12:13

标签: sql-server join union

此致

我有以下表格

客户端

id, name, saler1, saler2, saler3, dateSale...

人员

id, name...

我的查询是

select S1.*, S2.* 
from Client C 
left join Personnel S1.id on = C.saler1
left Join Personnel S2.id on = C.saler2

我的结果是

S1.id, S1.name ... S2.id, S2.name

但我只想要一列例如Personnel

|id | name |
|sa1| name |
|sa2| name |

有人可以帮助我吗?

2 个答案:

答案 0 :(得分:1)

不完全确定你在问什么,但是从你已经写过的查询中我认为你是在追求这样的......

Select *
FROM (
SELECT id, name, saler1 AS Saler, dateSale FROM Client Where saler1 IS NOT NULL
UNION ALL 
SELECT id, name, saler2 AS Saler, dateSale FROM Client Where saler2 IS NOT NULL
UNION ALL 
SELECT id, name, saler3 AS Saler, dateSale FROM Client Where saler3 IS NOT NULL
) C
Left join Personnel P  on P.id  = C.saler

因为这是你想要的另一种方式做同样的事情就是使用UNPIVOT之类的......

Select P.* , up.id, up.dated
FROM Client UNPIVOT (
                      Salers for Saler IN (Saler1,Saler2,Saler3)
                     )up
LEFT JOIN Personnel P ON up.Salers = P.id   

答案 1 :(得分:0)

我猜你正在寻找一个全联盟

select S1.* From Client C Left join Personnel S1.id on = C.saler1
UNION ALL
select S1.* From Client C Left join Personnel S1.id on = C.saler2