我正在尝试使用聚合事例来创建一个Pivot表。然而,对于我创建的表示行号的列,它显示了一个错误
代码:1056。无法在'rn'上分组。
同时,如果我手动执行相同的工作(通过将id列添加到表中,效果很好(。
这是代码:
CREATE TABLE employee (name varchar(128), occupation varchar(128));
INSERT INTO employee VALUES
('Sandra','Gydytoja'),
('Julija','Aktorė'),
('Marija','Aktorė'),
('Martyna','Vadybininkė'),
('Aistė','Mokytoja'),
('Kristina','Mokytoja'),
('Virginija','Mokytoja'),
('Jurga','Aktorė'),
('Justina','Gydytoja'),
('Mia','Vadybininkė');
SELECT ROW_NUMBER() OVER (PARTITION BY occupation ORDER BY name asc) AS rn,
MAX(case when occupation = "Gydytoja" then name end) AS Gydytoja,
MAX(case when occupation = "Aktorė" then name end) AS Aktorė,
MAX(case when occupation = "Vadybininkė" then name end) AS Vadybininkė,
MAX(case when occupation = "Mokytoja" then name end) AS Mokytoja
FROM employee
GROUP BY rn;
提前感谢您的帮助!
您需要一个子查询来首先填充rn,然后可以使用它:
SELECT rn, MAX(case when occupation = "Gydytoja" then name end) AS Gydytoja, MAX(case when occupation = "Aktorė" then name end) AS Aktorė, MAX(case when occupation = "Vadybininkė" then name end) AS Vadybininkė, MAX(case when occupation = "Mokytoja" then name end) AS Mokytoja from ( select * , ROW_NUMBER() OVER (PARTITION BY occupation ORDER BY name asc) AS rn FROM employee ) t GROUP BY rn;
rn|Gydytoja|Aktorï|Vadybinikï|Mokytoja-:|:-------|:--------|:---------------|:--------1|Justina | Julija | Martyna | Aistï2|Sandra|Jurga|Mia|Kristina3|null|Marija|null|Virginija
db<gt;小提琴这里