-1

I have three tables enter image description here

enter image description here

enter image description here

I have executed this query:

SELECT 
`tbl_players`.`id` AS `player_id`
,`tbl_players`.`player_name`
,`tbl_sports`.`sports_name`
,`tbl_scores`.`score`
FROM `tbl_players`
LEFT JOIN `tbl_scores` ON `tbl_players`.`id`=`tbl_scores`.`player_id`
LEFT JOIN `tbl_sports` ON `tbl_players`.`sports_id`=`tbl_sports`.`sports_id`
ORDER BY `tbl_players`.`id` ASC

And I got this: enter image description here

Now I want this: enter image description here

Amin
  • 581
  • 2
  • 6
  • 25
  • 1
    Possible duplicate of [MySQL pivot table](https://stackoverflow.com/questions/7674786/mysql-pivot-table) – James Feb 05 '19 at 06:20

5 Answers5

1

use conditional aggregation

select player_id,player_name,sports_name,
       sum(case when season=1 then score end) as season1_score,
       sum(case when season=2 then score end) as season2_score,
       sum(case when season=3 then score end) as season3_score
from
(
SELECT 
`tbl_players`.`id` AS `player_id`
,`tbl_players`.`player_name`
,`tbl_sports`.`sports_name`
,`tbl_scores`.`score`,`tbl_scores`.`season`
FROM `tbl_players`
LEFT JOIN `tbl_scores` ON `tbl_players`.`id`=`tbl_scores`.`player_id`
LEFT JOIN `tbl_sports` ON `tbl_players`.`sports_id`=`tbl_sports`.`sports_id`
)A group by player_id,player_name,sports_name
Fahmi
  • 36,607
  • 5
  • 19
  • 28
1

use conditional aggregation

 SELECT 
    `tbl_players`.`id` AS `player_id`
    ,`tbl_players`.`player_name`
    ,`tbl_sports`.`sports_name`
    , sum(case when tbl_scores.season=1 then `tbl_scores`.`score` end) as season1score
   ,sum(case when tbl_scores.season=2 then `tbl_scores`.`score` end) as season2score
,sum(case when tbl_scores.season=3 then `tbl_scores`.`score` end) as season3score
    FROM `tbl_players`
    LEFT JOIN `tbl_scores` ON `tbl_players`.`id`=`tbl_scores`.`player_id`
    LEFT JOIN `tbl_sports` ON `tbl_players`.`sports_id`=`tbl_sports`.`sports_id`
group by `tbl_players`.`player_name`
    ,`tbl_sports`.`sports_name`,player_id
Zaynul Abadin Tuhin
  • 30,345
  • 5
  • 25
  • 56
0

This might help.

You need to PIVOT your data

SELECT 
 player_id,
 player_name,
 sports_name,
 sum(case when tbl_scores.season=1 then `tbl_scores`.`score` end) as season1score,
 sum(case when tbl_scores.season=2 then `tbl_scores`.`score` end) as season2score,
 sum(case when tbl_scores.season=3 then `tbl_scores`.`score` end) as season3score
from 
  tbl_players
left join  tbl_sports 
  on `tbl_players`.`id`=`tbl_scores`.`player_id`
left join sports 
  on `tbl_players`.`sports_id`=`tbl_sports`.`sports_id`
group by
 layer_id,
 player_name,
 sports_name,
Derviş Kayımbaşıoğlu
  • 26,360
  • 3
  • 47
  • 64
-1

Use “distinct” selection to not get duplicates.

Just add “DISTINCT” right after “SELECT” in your query.

Example: SELECT DISTINCT column1, column2, ... FROM table_name;

Chao1920
  • 135
  • 1
  • 8
-1

I believe you should use inner join instead of left join