在SQL Server 2005
,Oracle 9
和PostgreSQL 8.4
(或以上):
WITH q AS
(
SELECT employeeId, managerId, ROW_NUMBER() OVER (PARTITION BY employeeID ORDER BY managerId) AS rn
FROM mytable
)
SELECT q1.employeeId, q1.managerName, q2.managerName, q3.managerName, q4.managerName
FROM q q1
JOIN q q2
ON q2.employeeId = q1.employeeId
AND q2.rn = 2
JOIN q q3
ON q3.employeeId = q1.employeeId
AND q3.rn = 3
JOIN q q4
ON q4.employeeId = q1.employeeId
AND q4.rn = 4
WHERE q1.rn = 1
在MySQL
:
SELECT employeeId,
(
SELECT managerName
FROM mytable mi
WHERE mi.employeeId = md.employeeId
ORDER BY
mi.employeeId, mi.managerId
LIMIT 0, 1
) AS manager1,
(
SELECT managerName
FROM mytable mi
WHERE mi.employeeId = md.employeeId
ORDER BY
mi.employeeId, mi.managerId
LIMIT 1, 1
) AS manager2,
(
SELECT managerName
FROM mytable mi
WHERE mi.employeeId = md.employeeId
ORDER BY
mi.employeeId, mi.managerId
LIMIT 2, 1
) AS manager3,
(
SELECT managerName
FROM mytable mi
WHERE mi.employeeId = md.employeeId
ORDER BY
mi.employeeId, mi.managerId
LIMIT 3, 1
) AS manager4
FROM (
SELECT DISTINCT employeeId
FROM mytable
) md
您的查詢是什麼樣的? – Lazarus 2010-10-05 13:41:26
這是一個奇怪的樹形結構數據庫表...而不是與管理人員,僱員(管理人員也是員工)和他們之間的關係表。但這與你的問題無關。 – 2010-10-05 13:49:08
哪個sql方言? – Beth 2010-10-05 15:31:35