我试图从SQL Server 2008中的Persons
表中加入此人和他的伙伴,但我不知道如何编写查询。
以下是好友选择的规则:
这是Persons
表:
根据上述规则,这应该是最终输出:
我试图写这样的查询:
SELECT p.ID, p.Name, b.Name
FROM persons AS p
INNER JOIN persons AS b ON
CASE
WHEN p.boss = b.id THEN 1
WHEN p.buddy = b.id THEN 1
ELSE 0
END = 1
但这不会返回我期望的结果。
PS:如果您想自己尝试,这是创建脚本:
CREATE TABLE Persons
([ID] int, [Name] varchar(4), [Boss] int, [Buddy] int)
;
INSERT INTO Persons
([ID], [Name], [Boss], [Buddy])
VALUES
(1, 'Tom', 0, 0),
(2, 'Jack', 1, 0),
(3, 'Emil', 0, 2),
(4, 'Evan', 2, 3)
;
答案 0 :(得分:2)
select a.id, a.name, b.name
from persons a
inner join persons b
on case when a.buddy <> 0 then A.buddy
when a.boss <> 0 then a.boss
else (Select min(ID) from Persons where ID <> A.ID) end = B.ID
答案 1 :(得分:0)
看起来你有一个等级,老板优先于好友:
select p.ID, p.Name, b.Name
from persons as p
INNER JOIN persons as b ON
(CASE WHEN p.boss > 0 THEN p.boss
WHEN p.boss = 0 AND p.buddy > 0 then p.buddy
ELSE (select top 1 from persons p1 where p1.ID <> p.ID)
END) = b.ID
如果定义了老板和好友,这将加入老板