听起来您需要对数据进行反透视。反透视的过程将多列转换为多行。您没有指定您使用的数据库,所以我将提供一些解决方案。
假设您有以下示例数据:
create table yourtable
(
id int,
name varchar(50),
class1 varchar(50),
class2 varchar(50),
class3 varchar(50),
class4 varchar(50)
);
insert into yourtable
values
(1, 'John', 'Science', 'Math', 'Chem', 'Physics'),
(2, 'Bob', 'Math', 'SS', 'Bio', 'Chem'),
(3, 'Jim', 'Econ', 'Math', 'Bio', 'Sci'),
(4, 'Sally', 'Crim', 'Bio', 'Math', 'Chem');
如果您的数据库没有像 SQL Server、Oracle 这样的 UNPIVOT 函数,那么您可以使用 UNION ALL 查询来获取结果:
select id, name, 'class1' col, class1 value
from yourtable
union all
select id, name, 'class2' col, class2 value
from yourtable
union all
select id, name, 'class3' col, class3 value
from yourtable
union all
select id, name, 'class4' col, class4 value
from yourtable;
见SQL Fiddle with Demo
如果您使用的是支持 UNPIVOT 功能的数据库,查询的语法将类似于:
select id, name, col, value
from yourtable
unpivot
(
value
for col in (class1, class2, class3, class4)
) unpiv