简体   繁体   English

MySQL查询(扩展二变量主键/数据透视)

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

In MySQL, suppose I have a table called 'data' with columns 'x', 'y', and 'value' 在MySQL中,假设我有一个名为“数据”的表,其中有列“ x”,“ y”和“值”

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. 并假设(x,y)是主键。

Is there a SELECT query I can run such that the output is 是否有我可以运行的SELECT查询,使得输出为

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). 我将知道'y'的可能值,以便可以将其硬编码到查询中(尽管如果查询更通用,我当然会更喜欢它)。

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 可以在以下位置找到有关数据透视表及其在MySql中生成方法的很好的解释: 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! 虽然您确实需要“自定义” SQL来为数据透视表指定列名,但是如果您事先不知道它们,则可以使用SQL为您生成它们! Check out the article! 查看文章!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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