如何翻转/重新组织从SQL select语句中检索的数据?

时间:2013-07-30 20:00:09

标签: sql oracle select

现在,我有一个SQL查询,它以下列方式返回数据: What I have

“SCHOOL”和“TEACHER”列中都有重复值,例如: A学校和C学校都有名叫史密斯女士的老师。

我需要以这种方式呈现我的数据:

What I want

是否可以直接在SQL select语句中执行此类操作(如果不可能,可以使用或不使用动态列名称)?我对每种方法的看法有何不同?我能得到一些例子吗?

我原来的选择语句非常复杂,我不想发布它,因为这个问题不会与其他任何人相关。所以我一般都会问,怎么会这样做呢?

2 个答案:

答案 0 :(得分:0)

这应该这样做:

select School, 
sum(case Teacher = 'Ms. Smith' then [# Students] else 0 end) as [Ms. Smith],
sum(case Teacher = 'Mr. Rogers' then [# Students] else 0 end) as [Mr. Rogers],
sum(case Teacher = 'Mr. Berkenheim' then [# Students] else 0 end) as [Mr. Berkenheim],
sum(case Teacher = 'Ms. Roberts' then [# Students] else 0 end) as [Ms. Roberts]
group by School

答案 1 :(得分:0)

如果您使用的是SQL Server 2005或更高版本,则可以使用PIVOT运算符。像这样:

SELECT
    School,
    [Ms. Smith],
    [Mr. Rogers],
    [Mr. Berkenheim],
    [Ms. Roberts],
    [Mr. Ashby],
    [Ms. Robinson]
FROM <data_table> AS D
PIVOT (
    SUM(NumberOfStudents) FOR Teacher IN ([Ms. Smith],[Mr. Rogers],[Mr. Berkenheim],[Ms. Roberts],[Mr. Ashby],[Ms. Robinson])
) P