简体   繁体   中英

MySQL query (expanding two-variable primary key / pivoting data)

In MySQL, suppose I have a table called 'data' with columns 'x', 'y', and 'value'

data:

x y  value
A D  0.5
A E  0.8
A F  4.2
B D  3.1
C F  1.6

And suppose (x,y) is the primary key.

Is there a SELECT query I can run such that the output is

X   D    E    F
A  0.5  0.8  4.2
B  3.1  n/a  n/a
C  n/a  n/a  1.6

I will know the possible values of 'y' so that can be hard-coded into the query (although I would of course prefer it if the query was more general).

Thanks.

What you want is called a "Pivot Table".

A nice explanation of Pivot tables and ways of generating them in MySql may be found at: http://dev.mysql.com/tech-resources/articles/wizard/index.html

Though you do need "custom" SQL to specify the column names for your pivot table if you don't know them in advance you can use SQL to generate them for you! Check out the article!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM