0

Good day,

I have a problem regarding how to build my query in MYSQL. I have this raw data.

ID       | NAME | VALUE | DESCRIPTION
ID-0001  | ARV1 | 10200 | First description
ID-0002  | ARV2 | 10300 | Second description
ID-0001  | ARV1 | 10400 | Added Description

And I want to achieve an output like this: Where I want to merge the datas with the same ID and put the other tables in another column and with new column name.

ID       | NAME | VALUE 1 | DESCRIPTION  1      |  VALUE 2 |  DESCRIPTION 2     |
ID-0001  | ARV1 | 10200   | First description   |  10400   |  Added Description |
ID-0002  | ARV2 | 10300   | Second description  |          |                    |

I badly need help. Thanks!

blizzy
  • 55
  • 6

2 Answers2

1

ID wise row is serialized as per storing data in DB that's why ORDER BY is not use. This query is alternative of PIVOT. But if more row exists for a same ID then PIVOT is better option. If any primary key is existed in table then use that PK at ORDER BY clause after PRTITION BY.

-- MySQL (v5.8)
SELECT t.id
     , MAX(t.name) name
     , MAX(CASE WHEN t.row_num = 1 THEN value END) value1
     , MAX(CASE WHEN t.row_num = 1 THEN description END) description1
     , MAX(CASE WHEN t.row_num = 2 THEN value END) value2
     , MAX(CASE WHEN t.row_num = 2 THEN description END) description2
FROM (SELECT *
           , ROW_NUMBER() OVER (PARTITION BY id) row_num
      FROM test) t
GROUP BY t.id;

Please check from url https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=e4a5999a3536b9e042d7ed92fc392de7

Suppose table have a primary key column name p_id. Then ROW_NUMBER() will

ROW_NUMBER() OVER (PARTITION BY id ORDER BY p_id) row_num

N.B: By default p_id sorts the data in ascending order but if need descending order then use DESC.

Rahul Biswas
  • 3,207
  • 2
  • 10
  • 20
1
WITH 
cte AS (
    SELECT *, ROW_NUMBER() OVER (PARTITION BY ID, NAME ORDER BY rowid) rn
    FROM test
)
SELECT t1.ID, t1.NAME, 
       t1.VALUE value1, t1.DESCRIPTION description1, 
       t2.VALUE value2, t2.DESCRIPTION description2
FROM cte t1
LEFT JOIN cte t2 ON t1.ID = t2.ID
                AND t1.NAME = t2.NAME
                AND t2.rn = 2
WHERE t1.rn = 1;

https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=e10ac4664ef614300c23a987f83e805d

PS. If a column which defines the rows priority not exists (rowid in the fiddle - it can be, for example, the creation datetime or something else) then the data order of the values pairs is not determined.

Akina
  • 39,301
  • 5
  • 14
  • 25