由于您提到Name
a 最多可以有5 Skills
,因此可以使用静态查询来解决此问题。
-- <<== PART 2
SELECT Name,
MAX(CASE WHEN RowNumber = 1 THEN Skill END) Skill_1,
MAX(CASE WHEN RowNumber = 2 THEN Skill END) Skill_2,
MAX(CASE WHEN RowNumber = 3 THEN Skill END) Skill_3,
MAX(CASE WHEN RowNumber = 4 THEN Skill END) Skill_4,
MAX(CASE WHEN RowNumber = 5 THEN Skill END) Skill_5
FROM
( -- <<== PART 1
SELECT a.Name,
b.Skill,
(
SELECT COUNT(*)
FROM Skill c
WHERE c.id = b.id AND
c.Skill <= b.Skill) AS RowNumber
FROM Name a
INNER JOIN Skill b
ON a.id = b.id
) x
GROUP BY Name
输出
╔══════╦═════════╦═════════╦═════════╦═════════╦═════════╗
║ NAME ║ SKILL_1 ║ SKILL_2 ║ SKILL_3 ║ SKILL_4 ║ SKILL_5 ║
╠══════╬═════════╬═════════╬═════════╬═════════╬═════════╣
║ jon ║ C++ ║ CSS ║ HTML ║ Java ║ JS ║
║ mary ║ Perl ║ PHP ║ Ruby ║ (null) ║ (null) ║
╚══════╩═════════╩═════════╩═════════╩═════════╩═════════╝
简要说明
让我们分解一下。查询中有两个部分。
查询的第一部分是PART 1Skill
,它为每个生成数字序列Name
。ROW_NUMBER
它只是使用相关子查询来模仿MySQL
不支持的窗口函数。
第二部分PART 2根据PART 1上生成的序号将行转置为列。它用于CASE
测试数字的值并返回数字Skill
上的关联。如果数字不匹配,则返回一个NULL
值。接下来,它聚合每组Name
使用的列,MAX()
因此SKILL
将返回而不是NULL
如果有的话。
更新 1
SELECT Name,
MAX(CASE WHEN RowNumber = 1 THEN Skill END) Skill_1,
MAX(CASE WHEN RowNumber = 1 THEN Level END) Level_1,
MAX(CASE WHEN RowNumber = 2 THEN Skill END) Skill_2,
MAX(CASE WHEN RowNumber = 2 THEN Level END) Level_2,
MAX(CASE WHEN RowNumber = 3 THEN Skill END) Skill_3,
MAX(CASE WHEN RowNumber = 3 THEN Level END) Level_3,
MAX(CASE WHEN RowNumber = 4 THEN Skill END) Skill_4,
MAX(CASE WHEN RowNumber = 4 THEN Level END) Level_4,
MAX(CASE WHEN RowNumber = 5 THEN Skill END) Skill_5,
MAX(CASE WHEN RowNumber = 5 THEN Level END) Level_5
FROM
(
SELECT a.Name,
b.Skill,
(
SELECT COUNT(*)
FROM Skill c
WHERE c.id = b.id AND
c.skill <= b.skill) AS RowNumber,
b.Level
FROM Name a
INNER JOIN Skill b
ON a.id = b.id
) x
GROUP BY Name
输出
╔══════╦═════════╦═════════╦═════════╦═════════╦═════════╦═════════╦═════════╦═════════╦═════════╦═════════╗
║ NAME ║ SKILL_1 ║ LEVEL_1 ║ SKILL_2 ║ LEVEL_2 ║ SKILL_3 ║ LEVEL_3 ║ SKILL_4 ║ LEVEL_4 ║ SKILL_5 ║ LEVEL_5 ║
╠══════╬═════════╬═════════╬═════════╬═════════╬═════════╬═════════╬═════════╬═════════╬═════════╬═════════╣
║ jon ║ C++ ║ 3 ║ CSS ║ 4 ║ HTML ║ 5 ║ Java ║ 2 ║ JS ║ 5 ║
║ mary ║ Perl ║ 1 ║ PHP ║ 4 ║ Ruby ║ 3 ║ (null) ║ (null) ║ (null) ║ (null) ║
╚══════╩═════════╩═════════╩═════════╩═════════╩═════════╩═════════╩═════════╩═════════╩═════════╩═════════╝