Query sql row to column

Query statement, the classic usage of row-to-column Whether the

teacher 's week number has lesson
 1 2 has
 1 3 has
 2 1 has
 3 2 has`
 1 2 has

Write a sql statement to make you become such a table

Teacher's number Monday Tuesday Wednesday
 1 2 1 
 2 1   
 3 1

The numbers under each week indicate: the number of lessons that the corresponding teacher has arranged on the day of the week. The

database table information is as follows:



Simple SQL
select a.teacherid as teacher number, sum(a.w1) ​​Monday, sum(a.w2) Tuesday, sum(a.w3) Wednesday from(
select teacherid,case when week=1 then 1 end w1, case when week=2 then 1 end w2,case when week=3 then 1 end w3  from course) a  group by teacherid


complex SQL
select b.teacherid, sum(w1) as Monday, sum(w2) Tuesday, sum(w3) Wednesday from (
select a.teacherid,case  when a.week=1  then a.num end as w1,case  when a.week=2  then a.num end as w2, case  when a.week=3  then a.num end as w3 from (select teacherid,week,count(*) as num from course group by teacherid,week) a) b group by b.teacherid

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326946271&siteId=291194637