Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
295 views
in Technique[技术] by (71.8m points)

pivot - mysql converting multiple rows into columns in a single row

i have a details table with columns:

  • user_id int
  • code int
  • value int

And i want to build a summary table that looks like:

  • user_id int
  • valueA int
  • valueB int

In the details table, valueA would correspond to say, code 5, and valueB would correspond to say, code 6, so i'm looking for something like:

insert into summary (user_id,valueA,valueB) VALUES ( SELECT ??? from details );

The problem of course is that i'm looking at multiple rows from the "details" table to populate one row in the "summary" table.

Eg, if i had the following rows in details:

1  5  100
1  6  200
2  5  1000
2  6  2000

I want to end up with the following in the summary table:

1  100   200
2  1000  2000

Any ideas?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

MySQL doesn't have PIVOT/UNPIVOT syntax, which leaves you to use a combination of GROUP BY and CASE expressions:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...