假设我有以下示例数据集:
emplid | Citizenship |
100001 | USA |
100001 | CAN |
100001 | CHN |
100002 | USA |
100002 | CHN |
100003 | USA |
我想把它排成一排显示每个雇员的公民身份。我们可以假设一个雇员有四个公民身份。输出如下:
emplid | Citizeship_1 | Citizenship_2 | Citizenship_3
100001 | USA | CHN | CAN
100002 | USA | CHN |
100003 | USA | |
唯一可行的解决方案是:
SELECT e.emplid, MAX(e.citizenship) AS citizenship1,
MAX(e1.citizenship) AS citizenship2,
MAX(e2.citizenship) AS citizenship3,
MAX(e3.citizenship) AS citizenship4
FROM employee e
LEFT JOIN employee e1 ON e1.emplid = e.emplid AND e1.citizenship < e.citizenship
LEFT JOIN employee e2 ON e2.emplid = e1.emplid AND e2.citizenship < e1.citizenship
LEFT JOIN employee e3 ON e3.emplid = e2.emplid AND e3.citizenship < e2.citizenship
GROUP BY e.emplid
随着数据集的增长,效率越来越低,但我找不到重写此查询的方法。
最佳答案
为什么不把公民身份列成一个名单呢?
select e.emplid, group_concat(citizenship) as citizenships
from employee e
group by e.emplid;
如果希望有四个单独的列,可以执行以下操作:
select e.emplid,
substring_index(group_concat(citizenship), ',', 1) as c1,
(case when count(*) >= 2
then substring_index(substring_index(group_concat(citizenship), ',', 2), ',', -1)
end) as c2,
(case when count(*) >= 3
then substring_index(substring_index(group_concat(citizenship), ',', 3), ',', -1)
end) as c3,
(case when count(*) >= 4
then substring_index(substring_index(group_concat(citizenship), ',', 4), ',', -1)
end) as c4
from employee e
group by e.emplid;
关于mysql - 我该如何改善这4位数的自我加入?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26786560/