MySQL dynamic transpose/pivot of a table

2019-09-18 18:44发布

问题:

I've been trying to pivot a very sample table:

TYPE       | COUNT
___________________
'CHAINS'   | '38'
'INDEP'    | '64'
'SUPER'    | '25'

Yup, it's that simple. I've been reading tutorials, Stackoverflow answers and I've been looking for a good tutorial about transposing a table. I just can't understand it very well and I haven't been able to accomplish the following result:

CHAINS | INDEP | SUPER
_______________________
38     | 64    | 25

I know there are other questions similar to this one, but I just can't get the point from reading. Most examples use multiple tables to explain or just have code with no explanmation, and I can't undestrand what's needed to do this. Can somebody please explain me in detail how can I accomplish this pivoted table??

THANKS A LOT!!


EDIT 1:

With the tutorials I've read, I've manage to get the following:

CHAINS | INDEP | SUPER
_______________________
38     | NULL  | NULL
NULL   | 64    | NULL
NULL   | NULL  | 25

I'd like the data to be in a single row without those null. I know there are tutorials and answers about this but I just don't understand clearly. I'd like an explanation of whats the logic to do this pivot table.

@bluefeet told me I needed an aggregate function. With sum() I got a single row


EDIT 2:

This is the query I'm using works (thansk to @bluefeet) but it's not dynamic: I can't know for sure what columns I'll need.

SELECT
  sum(case when sq.TYPE = 'CHAINS' then sq.COUNT end) AS CHAINS,
  sum(case when sq.TYPE = 'INDEP' then sq.COUNT end) AS INDEPE,
  sum(case when sq.TYPE = 'SUPER' then sq.COUNT end) AS SUPER
from subquery1 sq

How can I get a similar result but with a dynamic query? THANKS