假设我有下表,名为GPAs
:
name | semester | GPA
Joe Winter 3.5
Joe Spring 4.0
如何在一个查询中返回以下内容?
name | gpaWinter | gpaSpring
Joe 3.5 4.0
答案 0 :(得分:2)
select name,
max(case when semester = 'Winter' then GPA end) as gpaWinter,
max(case when semester = 'Spring' then GPA end) as gpaSpring
from GPAs
group by name
答案 1 :(得分:1)
SELECT name, (SELECT GPA FROM GPAs WHERE name = t1.name AND semester = 'Winter') AS `gpaWinter`, (SELECT GPA FROM GPAs WHERE name = t1.name AND semester = 'Spring') AS `gpaSpring` FROM GPAs t1
但你真的不应该在SQL中这样做。 SQL的目的是检索数据;将其格式化以便显示是应用程序代码的工作。
答案 2 :(得分:1)
SELECT name,GROUP_CONCAT(semester) AS semesters,GROUP_CONCAT(GPA) AS GPAs
FROM GPAs
GROUP BY name
这将返回如下行:
name | semesters | GPAs
Joe Winter,Spring 3.5,4.0
然后你可以解析学期和GPA。
您还可以执行GROUP_CONCAT(semester,'=',GPA) as GPAs
之类的操作,它将返回:
name | GPAs
Joe Winter=3.5,Spring=4.0
然后你可以解析GPAs行。