If you’ve been looking at database threads here for any length of time, you’re probably used to seeing questions where someone has a table laid out like this:
It’s not pretty (or easy to maintain), but a bunch of union queries put together will get the job done.
But what about going the other way around? Is there an SQL statement that will take the second table structure and output the first one? Someone on another message board asked about this and (after giving them the appropriate warning about not replacing the good table design with a bad one) I had to recommend using an imperative language of some kind. I don’t think this can be done in straight SQL. Am I wrong? Don’t assume that every thing/type combination shows up in the second table.
Sometimes it seems like CASE expressions are the answers to half the SQL questions I am asked at work.
select
'TYPE1' as type1,
case type when 'TYPE1' then amount else null end as amount1,
'TYPE2' as type2,
case type when 'TYPE2' then amount else null end as amount2
/* etc. */
from things_types ;
P.S. “pivot table SQL” would be a good search term for this kind of query
Yep, as Arnold Winkelried said, this is a classic pivot query. You shouldn’t need a self-join for every type; one run through the table is good enough. It is true that you need to know every type ahead of time tho, and that every time a new type is added, the query must be updated.
That type is, and it’s supported by every major database system that I’m familiar with. Some vendor-specific implementations have better options, eg. Microsoft SQL Server 2005’s PIVOT function (newer versions of Oracle have something like this, too). So check your product documentation!
Don’t forget to group on thingID when implementing Arnold Winkelreid’s solution, or you’ll end up with the same number of rows, but with additional columns, most of which aren’t populated.