我有2张桌子(1.Employee 2.Family)。 我想写一个产生以下输出的sql语句。
图片
Url : http://www.enterupload.com/8ryuew2anq0q/QUESTION1.jpg.html
Mirror 1 : http://www.freeimagehosting.net/image.php?c9bea5b6b6.png
Mirror 2 : http://0k.010.img98.com/out.php/i342669_QUESTION1.png
link text http://0k.010.img98.com/out.php/i342669_QUESTION1.png
答案 0 :(得分:1)
看起来只是左边加入我。
SELECT Family.Name, Family.Relative, Employee.Id
FROM Employee
LEFT JOIN Family ON Employee.ID = Family.EmployeeID
如果您真的想要第一个列为id并且是新的唯一编号,请尝试使用
SELECT ROW_NUMBER() OVER (ORDER BY COALESCE(Family.ID,9999999) ASC, Employee.ID ASC) AS ID, Family.Name, Family.Relative, Employee.Id as EmployeeID
FROM Employee
LEFT JOIN Family ON Employee.ID = Family.EmployeeID
答案 1 :(得分:0)
这会得到您想要的结果。不知道为什么你会想要他们! (特别是完全由id组成的值9和10)
;WITH Employee AS
(
select 1 as ID, 'Alex' AS Name UNION ALL
select 2 as ID, 'James' AS Name UNION ALL
select 3 as ID, 'John' AS Name UNION ALL
select 4 as ID, 'Anthony' AS Name UNION ALL
select 5 as ID, 'Jack' AS Name
),
Family AS
(
SELECT 1 AS ID, 'Kayla' AS Name, 'wife' AS Relative, 1 AS EmployeeID UNION ALL
SELECT 2, 'Benjamin', 'Son',1 UNION ALL
SELECT 3, 'Alyssa', 'wife',2 UNION ALL
SELECT 4, 'Emma', 'daughter',2 UNION ALL
SELECT 5, 'Emily', 'daughter',2 UNION ALL
SELECT 6, 'Elizabeth', 'wife',5 UNION ALL
SELECT 7, 'Jackson', 'Son',5 UNION ALL
SELECT 8, 'Laura', 'daughter',5
),
cte AS
(
SELECT f.ID, f.Name, f.Relative, e.ID EmployeeID,
MAX(f.ID) OVER() + ROW_NUMBER() OVER (PARTITION BY f.ID ORDER BY e.ID) AS RN
FROM Employee e LEFT OUTER JOIN Family f
ON e.ID = f.EmployeeId
)
SELECT COALESCE(ID,RN) AS ID, Name, Relative, EmployeeID
FROM cte
ORDER BY ID