现在,我有一个SQL查询,它以下列方式返回数据:
“SCHOOL”和“TEACHER”列中都有重复值,例如: A学校和C学校都有名叫史密斯女士的老师。
我需要以这种方式呈现我的数据:
是否可以直接在SQL select语句中执行此类操作(如果不可能,可以使用或不使用动态列名称)?我对每种方法的看法有何不同?我能得到一些例子吗?
我原来的选择语句非常复杂,我不想发布它,因为这个问题不会与其他任何人相关。所以我一般都会问,怎么会这样做呢?
答案 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