Skip to main content

Query Pivot in MySQL

Basically this blog post is about dynamic columns in MySQL queries.  Since you can't run "pivot" queries in MySQL, how do you write queries that return an arbitrary number of columns (perhaps based on the number of rows in another table)?

The answer is simple: you can't... at least not in a single query.  The best way to do this is to run two queries and generate the SQL for the 2nd query based on the results of the 1st query.

Imagine this table of product sales:

ProductIDCustomerIDUnit Sales
1120
1250
2120
2270
2390

Maybe you want your result set to look like this...
ProductIDCustomer 1Customer 2Customer 3
120500
2207090

Write this query first:

SELECT CustomerID, CustomerName FROM `customers`

Store the results into $rows.  For each $row, append this string to $fields:
", SUM(CASE WHEN CustomerID=$row[0] THEN `Unit Sales` ELSE 0 END) AS $row[1]"

Then... write this query:

"SELECT ProductID $fields
FROM `sales`
GROUP BY ProductID"

Done.  This pattern is not recommended, but sometimes you might find this to be useful for custom reporting.  Also, I can guarantee that this performs WAY better than multiple joins.  Plus, MySQL places a limit on the maximum number of table joins you can have in a query... at the time of this writing, the limit is 61.  Cheers!

Comments

Popular posts from this blog

Developing a lightweight WebSocket library

Late in 2016, I began development on a lightweight, isomorphic WebSocket library for Node.js called ws-wrapper .  Today, this library is stable and has been successfully used in many production apps. Why?  What about socket.io ?  In my opinion, socket.io and its dependencies are way too heavy .  Now that the year is 2018, this couldn't be more true.  Modern browsers have native WebSocket support meaning that all of the transports built into the socket.io project are just dead weight.  On the other hand, ws-wrapper and its dependencies weigh about 3 KB when minified and gzipped.  Similarly, ws-wrapper consists of about 500 lines of code; whereas, socket.io consists of thousands of lines of code.  As Dijkstra once famously said: "Simplicity is prerequisite for reliability." ws-wrapper also provides a few more features out of the box.  The API exposes a two-way, Promise-based request/response interface.  That is, clients can request dat...

Wedding Prediction - October, 2013

Carla and I are planning on getting married sometime in October next year.  We need to pick a date, and that decision may  involve some science and mathematics.  :) For example, we want the weather to be nice.  To be more precise, we'd like the high temperature for the wedding day to be between 60 and 80 degrees Fahrenheit.  Obviously, we have both lived in Ohio our entire lives, and we have a pretty good idea of what the weather will be like.  We both hypothesised that October was a "hit or miss" sort of month; it could be cold, or it could be nice. But, for me, a simple hypothesis was not enough; I really wanted to know the probabilities of decent weather based on historical weather data.  Many websites on the Internet (i.e. almanac.com) charge you to review historical weather data, but Carla and I discovered a cool page on cleveland.com that provided exactly what we wanted.  I loaded the historical temperature data from 1903 to 2011 f...

Node.JS + MySQL + Transactions

If you're like me, then you are probably building web applications using Node.JS and MySQL (and maybe Redis, too).  If so, you're probably going to need transactions, and you've probably already noticed that the current version of node-mysql doesn't support transactions yet.  :( But that's OK because I have a solution for you.  Check out node-mysql-queues on github .  This project provides pretty good support for MySQL transactions with a fairly simple API.  There are a couple of things to remember, though.  For one, Node.JS is very "callback-centric," so when executing a series of queries, you would normally chain the queries together with a series of callbacks.  node-mysql sort of changes this model, by allowing you to place queries on a queue to be executed in order.  If you only care about doing something when all of your queries are done, you can simply put your callback in the final query.  node-mysql-queues allows you to do the same...