简体   繁体   中英

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. 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? 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 .

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