How to rotate rows into columns in MySQL

I have answered a lot of MySQL pivot questions over on Stack Overflow and a few over on Database Administrators and have learned some things about how to transform data in MySQL. Unfortunately, MySQL does not have PIVOT function, so in order to rotate data from rows into columns you will have to use a CASE expression along with an aggregate function. Let’s set up some sample data. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 create table products ( prod_id int not null, prod_name varchar(50) not null, primary key (prod_id) ); insert into products (prod_id, prod\name) values (1, 'Shoes'), (2, 'Pants'), (3, 'Shirt'); create table reps ( rep_id int not null, rep_name varchar(50) not null, primary key (rep_id) ); insert into reps (rep_id, rep_name) values (1, 'John'), (2, 'Sally'), (3, 'Joe'), (4, 'Bob'); create table sales ( prod_id INT NOT NULL, rep_id INT NOT NULL, sale_date datetime not null, quantity int not null, PRIMARY KEY (prod_id, rep_id, sale_date), FOREIGN KEY (prod_id) REFERENCES products(prod_id), FOREIGN KEY (rep_id) REFERENCES reps(rep_id) ); insert into sales (prod_id, rep_id, sale_date, quantity) values (1, 1, '2013-05-16', 20), (1, 1, '2013-06-19', 2), (2, 1, '2013-07-03', 5), (3, 1, '2013-08-22', 27), (3, 2, '2013-06-27', 500), (3, 2, '2013-01-07', 150), (1, 2, '2013-05-01', 89), (2, 2, '2013-02-14', 23), (1, 3, '2013-01-29', 19), (3, 3, '2013-03-06', 13), (2, 3, '2013-04-18', 1), (2, 3, '2013-08-03', 78), (2, 3, '2013-07-22', 69); We can easily query the rep, sales, and product data by joining the tables:

Did somebody say pivot?

Paging bluefeet, there is a PIVOT question to be answered. While that might seem like a joke, it has really happened, especially over on Stack Overflow. If you have seen any of my posts, then the chances are that I was answering a PIVOT question (or something similar). At this time of this post almost 20% of my total answers (over 3k) have been on pivot questions. You might ask yourself, why pivot?

Late to the party

Boy, I am sure behind the times with having a tech type of blog, but being late is better than never. I am going to try to use this platform to discuss some of my tech journeys while I delve into my new job as a DBA developer. I have worked on SQL Server in the past, but I will be venturing into Oracle development as well as more in depth SQL Server stuff.

About

Just a little blurb…I’m a former web and application developer, and Community Manager who is currently working as a Database Administrator at Stack Overflow. When I’m not at my desk, I’m probably running or pretending to be a woodworker. I can be reached via email at onlybluefeet (SHIFT+2) gmail (period) com*. * If you are human, you should be able to decipher the email address.