-2

I tried to search post. But i cant found it

I have table like this:

   +--------+----------+-----------+
   |   id   |   data1  |   data2   |
   +--------+----------+-----------+
   |  A123  |    A     |    315    |
   +--------+----------+-----------+
   |  A123  |    A     |    332    |
   +--------+----------+-----------+
   |  A123  |    A     |    220    |
   +--------+----------+-----------+
   |  C234  |    B     |    356    |
   +--------+----------+-----------+
   |  C234  |    B     |    224    |
   +--------+----------+-----------+
   |  C234  |    B     |    114    |
   +--------+----------+-----------+

I found like this:

   +--------+----------+-----------+-----------+
   |   id   |   data1  |        newdata        | 
   +--------+----------+-----------+-----------+
   |  A123  |    A     |       315,332,220     |
   +--------+----------+-----------+-----------+
   |  C234  |    B     |       356,224,114     |
   +--------+----------+-----------+-----------+

How do query the database something like:

   +--------+----------+-----------+-----------+-----------+
   |   id   |   data1  |  newdata1 |  newdata2 |  newdata3 |
   +--------+----------+-----------+-----------+-----------+
   |  A123  |    A     |    315    |    332    |    220    |
   +--------+----------+-----------+-----------+-----------+
   |  C234  |    B     |    356    |    224    |    114    |
   +--------+----------+-----------+-----------+-----------+

I just have 3 newdata (newdata1, newdata2, newdata3), no more

Thanks

vandalizm
  • 1
  • 1

1 Answers1

0

What you are looking for is often called 'horizontal pivoting', where a number of values, in several rows, belonging to a common identifier in the table, with a fix maximum number n of rows per identifier, is pivoted from 'vertical' to n columns horizontally.

I just answered a very similar questions the other day.

You will see that is based on a GROUP BY of the common identifier, and works with a SUM(CASE WHEN .. END) in case of measures, and, for example, a MAX(CASE WHEN ... END) in case of not-summable values. Here's my previous post:

How to go about a column with different values in a same row in sql?

Should you need something more specific matching exactly your example, just shout.

Happy playing -

Marco the Sane

Community
  • 1
  • 1
marcothesane
  • 6,192
  • 1
  • 11
  • 21