Search notes:

SQL Server: pivot

Creating a table

create table things (
   item     varchar(10),
   grp      varchar(10),
   val_one  integer,
   val_two  integer
);
Github repository about-MSSQL, path: /sql/select/pivot/use-operator/create-table.sql

Insert values

set nocount on
insert into things values('abc', 'foo',  7, 8);
insert into things values('abc', 'foo',  1, 3);

insert into things values('abc', 'bar',  2, 7);

insert into things values('abc', 'baz',  6, 2);
insert into things values('abc', 'baz', 11, 4);
insert into things values('abc', 'baz',  4, 6);

----------------------------------------------

insert into things values('def', 'foo',  4, 5);
insert into things values('def', 'foo', 11, 4);

insert into things values('def', 'bar',  9, 2);
insert into things values('def', 'bar',  5, 5);

insert into things values('def', 'baz', 12, 3);
Github repository about-MSSQL, path: /sql/select/pivot/use-operator/insert-values.sql

Select with pivot operator

select
   item,
   [foo] as sum_foo,
   [bar] as sum_bar,
   [baz] as sum_baz
from (
   select
      item,
      grp,
      val_one
   from
      things
) as t
pivot (
  sum(val_one) for grp in ([foo], [bar], [baz])
) as v1;
Github repository about-MSSQL, path: /sql/select/pivot/use-operator/select.sql

Cleaning up

drop table things;
Github repository about-MSSQL, path: /sql/select/pivot/use-operator/drop-table.sql

See also

select

Index

Fatal error: Uncaught PDOException: SQLSTATE[HY000]: General error: 8 attempt to write a readonly database in /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php:78 Stack trace: #0 /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php(78): PDOStatement->execute(Array) #1 /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php(30): insert_webrequest_('/notes/developm...', 1758207172, '216.73.216.150', 'Mozilla/5.0 App...', NULL) #2 /home/httpd/vhosts/renenyffenegger.ch/httpsdocs/notes/development/databases/SQL-Server/sql/select/pivot/index(100): insert_webrequest() #3 {main} thrown in /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php on line 78