Home > Software engineering >  Concatination table in MySql
Concatination table in MySql

Time:01-26

I need to write an SQL query that fetches something like this :

a b c
1 x 3
2 y 4
3 x 7
4 y 9

transforms into the following form:1

Here's my coding attempt:

SELECT CONCAT (a) AS a , CONCAT (b, -c) as m  FROM viborka

and the corresponding output I'm getting:

a m
1 x-3
2 y-4
3 x-7
4 y-9

I can't merge expressions with X into string 1 and expressions with Y into string 2.

How can I do it?

CodePudding user response:

You can do:

select
  case when row_number() over(partition by b order by c) = 1 then a end as a,
  concat(b, '-', c) as m
from t
order by b, c

Result:

 a     m   
 ----- --- 
 1     x-3 
 null  x-7 
 2     y-4 
 null  y-9 

See running example at db<>fiddle.

  • Related