目前正在解决一个挑战问题,我一直试图解决我面临的问题但却无法解决。您的专业知识将受到高度赞赏。
以下是问题:
旋转OCCUPATIONS中的Occupation列,以便每个Name按字母顺序排序并显示在其相应的Occupation下面。输出列标题应分别为Doctor,Professor,Singer和Actor。
我的解决方案
SELECT
[Doctor],
[Professor],
[Singer],
[Actor]
FROM
(SELECT
ROW_NUMBER() OVER (PARTITION BY Occupation ORDER BY Name) ma,
[Name],
[Occupations]
FROM
Occupation
) AS source
PIVOT
( MAX([Name]) FOR [occupation] IN ([Doctor],[Professor],[Singer],[Actor]) ) as pv
ORDER BY ma
错误消息
ERROR 1064 (42000) at line 5: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '[Doctor],
[Professor],
[Singer],
[Actor]
FROM
(SELECT
' at line 2
等待你的回复。感谢
答案 0 :(得分:3)
Mysql
不支持PIVOT
运营商
使用conditional aggregate
来转动数据。
由于名称被拆分为4个不同的列,因此在旋转数据后按名称排序并没有多大意义。
select
Occupations,
max(case when occupation = 'Doctor' then name end) as Doctor,
max(case when occupation = 'Professor' then name end) as Professor,
max(case when occupation = 'Singer' then name end) as Singer,
max(case when occupation = 'Actor' then name end) as Actor
from Occupation
Group by Occupations
您也应该使用反引号[]
``
答案 1 :(得分:0)
对于Mysql,可以这样解决:
set @d=0, @p=0, @s=0, @a=0;
select min(Doctor), min(Professor), min(Singer), min(Actor)
from(
select case
when Occupation='Doctor' then (@d:=@d+1)
when Occupation='Professor' then (@p:=@p+1)
when Occupation='Singer' then (@s:=@s+1)
when Occupation='Actor' then (@a:=@a+1)
end as Rowline,
case when Occupation='Doctor' then Name end as Doctor,
case when Occupation='Professor' then Name end as Professor,
case when Occupation='Singer' then Name end as Singer,
case when Occupation='Actor' then Name end as Actor
from OCCUPATIONS
order by Name
) as temp
group by Rowline;
希望这能解决您的问题。