Sql group query, how to turn the vertical display result into horizontal display

Build a library and enter data:
create table BookLibary
([Library] varchar(10),[Subject] varchar(10),[Quantity] int)
insert into BookLibary select'A
','Language',5
union all select'B ','Mathematics',6
union all select'C','English',3
union all select'B','language',4
union all select'A','mathematics',3

table data:
library subject quantity
---------- ---------- -----------
A Chinese 5
B Mathematics 6
C English 3
B Chinese 4
A Mathematics 3

Sql statement:
declare @execSql varchar(8000)
set @execSql='select [library]'
select @execSql=@execSql+',max(case when [subject]='''+[subject]
    +''' then [quantity] else'''' end) as'''+ [subject]
    +'''' from BookLibary group by [subject]
set @execSql=@execSql+'from BookLibary group by [library] '
print @execSql
exec(@execSql)

Finally @execSql looks like this:
select [library],
max(case when [subject]='mathematics' then [quantity] else'' end) as'mathematics',
max( case when [subject]='English' then [quantity] else'' end) as'English',
max(case when [subject]='language' then [quantity] else'' end)
as'language ' from BookLibary group by [Library]

Results:
Library Mathematics English Language
---------- ----------- ----------- -----------
A 3 0 5
B 6 0 4
C 0 3 0

Guess you like

Origin blog.csdn.net/zhangleiyes123/article/details/112866936