简体   繁体   English

将单列拆分为多列

[英]Split a single column into multiple columns

I'm currently struggling with a query for our project management software (it's a school project).我目前正在努力查询我们的项目管理软件(这是一个学校项目)。

I have the following Table:我有下表:

 projectID     |    cID          |    value
---------------|-------------------------
1              |     3           |     321
1              |     4           |     442
2              |     3           |     999
2              |     4           |     799

And the final product should look like this:最终产品应如下所示:

      c1       |     c2
---------------|-----------------
      321      |     442
      999      |     799

Now, the problem is that there can be an infinite number of c1, c2, etc. and an infinite number of projects.现在,问题是可以有无限多的 c1、c2 等和无限多的项目。 So the table will get quite big (in both directions).所以桌子会变得很大(在两个方向)。

Is there a way to let the columns declare "itself"?有没有办法让列声明“自身”? If not, lets say I restrict the number of c1, c2, .. to 5, how can I do it?如果没有,假设我将 c1、c2、.. 的数量限制为 5,我该怎么做? I tried something like:我试过类似的东西:

select v1.value, v2.value from value v1, value v2

I believe using conditional aggregation should get you your pivoted result:我相信使用条件聚合应该可以得到你的旋转结果:

select
  max(case when cid = 3 then value end) as c1,
  max(case when cid = 4 then value end) as c2,
  ...
from yourtable
group by projectid

Yes, there is a way to build dynamic statement within MySQL procedure by string manipulation and concatenation and then executing it using EXECUTE .是的,有一种方法可以通过字符串操作和连接在 MySQL 过程中构建动态语句,然后使用EXECUTE执行它。

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

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