我和一个人及其朋友之间有一个主要的细节关系:
人
id name
-- ------
1 Jones
2 Smith
3 Norris
朋友
id personId friendName
-- -------- ----------
1 1 Alice
2 1 Bob
3 1 Charly
4 1 Deirdre
5 2 Elenor
一个人可以拥有他想要的朋友。我想创建一个视图,与所找到的前三个朋友一起选择所有人;像这样的东西:
id name friend1 friend2 friend3
-- ---- ------- ------- -------
1 Jones Alice Bob Charly
2 Smith Elenor <null> <null>
3 Norris <null> <null> <null>
如何使用标准SQL执行此操作? (Microsoft SQL Server 2005)。
答案 0 :(得分:2)
SELECT p.Id, p.name,
MAX(CASE RowNum
WHEN 1 THEN
FriendName
ELSE
NULL
END) Friend1,
MAX(CASE RowNum
WHEN 2 THEN
FriendName
ELSE
NULL
END) Friend2,
MAX(CASE RowNum
WHEN 3 THEN
FriendName
ELSE
NULL
END) Friend3
FROM Person p
LEFT JOIN (SELECT id, PersonId, FriendName,
ROW_NUMBER() OVER(PARTITION BY PersonId ORDER BY id) RowNum
FROM Friends) f
ON f.PersonId = p.Id
GROUP BY p.Id, p.Name
结果:
1 Jones Alice Bob Charly
3 Norris NULL NULL NULL
2 Smith Elenor NULL NULL
答案 1 :(得分:0)
SELECT t1.id, t1.name,
(SELECT max(friendname)
FROM friends t2
WHERE t2.personid = t1.id)
"Friend1",
(SELECT max(friendname)
FROM friends t2
WHERE friendname < (SELECT max(friendname)
FROM friends t3
WHERE t3.personid = t1.id)
AND t2.personid = t1.id)
"Friend2",
(SELECT max(friendname)
FROM friends t2
WHERE friendname < (SELECT max(friendname)
FROM friends t3
WHERE friendname < (SELECT max(friendname)
FROM friends t4
WHERE t4.personid = t1.id)
AND t3.personid = t1.id)
AND t2.personid = t1.id)
"Friend3"
FROM person t1