开发者

How to transform rows into columns having no column with unique values?

I am trying to transform some rows into columns in MySQL. I know it has been asked and answered previously, like here.

My problem is, there is nothing in my rows on which I can apply the 'if' construct. (At least I think so.) E.g. For the following input,

2  5  1000
2  6  2000

I can run this query:

INSERT INTO SUMMARY
  (user_id,valueA,valueB) 
  SELECT d.user_id,
         MAX(CASE WHEN d.code = 5 THEN d.value ELSE NULL END),
         MAX(CASE WHEN d.code = 6 THEN d.value ELSE NULL END),
    FROM DETAILS d
GROUP BY d.user_id

and get this output:

2  1000  2000

But my problem 开发者_高级运维is, my input is something like this:

2  6  1000
2  6  2000

(The values in the second column are not unique.) And i still need the same output, i.e.:

2  1000  2000

Can it be done in MySQL? If yes, can anyone help me with this?


Well, if you don't have any idea of how many columns there will be in your pivot table, nor have a value to decide which value should go in a given column, the best solution I can recommend is to use a GROUP_CONCAT function and then do some parsing in your code:

SELECT d.user_id, GROUP_CONCAT(
    d.value SEPARATOR ','
  ) AS val
FROM details d
GROUP BY d.user_id;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜