Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL - Split two columns into two different rows

Tags:

sql

concat

mysql

I don't have any idea to create this sorry if it is a silly question.

I have a table two teams and total watch and I will use this information later a different place so my idea concat this two column in one column but two different rows:

HomeTeam      AwayTeam     Totalwatch 
A              B              100
A              C               90
C              A               80
D              B               70
C              E               50

Can I this

Teams          TotalWatch
A                100
B                100
A                 90
C                 90
C                 80
A                 80
D                 70
B                 70
C                 50
E                 50

I have a few columns so they will repeat as well.

Just a note I know how can concat in one-row use with concat function I do not know how can I make with two rows

like image 932
Axis Avatar asked Jan 03 '18 06:01

Axis


2 Answers

You can use UNION ALL and an ORDER BY Totalwatch DESC to get the results ordered according to Totalwatch.

SELECT HomeTeam AS Teams, Totalwatch  FROM YourTable
UNION ALL
SELECT AwayTeam, Totalwatch FROM YourTable
ORDER BY Totalwatch DESC;
like image 115
Jibin Balachandran Avatar answered Nov 02 '22 22:11

Jibin Balachandran


Simply use UNION ALL:

SELECT * 
FROM(
    SELECT HomeTeam Teams,TotalWatch FROM Your_Table
    UNION ALL
    SELECT AwayTeam,TotalWatch FROM Your_Table
    )D
ORDER BY TotalWatch DESC
like image 23
DineshDB Avatar answered Nov 03 '22 00:11

DineshDB