This type of data transformation is called a PIVOT. MySQL does not have a pivot function but you can use an aggregate function with a CASE
expression to get the result.
If the names of the clients
is known ahead of time, then you can hard-code the query:
select s.playdate,
sum(case when clname = 'Chris' then score end) Chris,
sum(case when clname = 'Gale' then score end) Gale,
sum(case when clname = 'Donna' then score end) Donna
from clients c
inner join scores s
on c.clid = s.clid
group by s.playdate;
See SQL Fiddle with Demo.
If you have an unknown number of clients or you will be adding new clients that you will want included without having to change the code, then you can use a prepared statement to generate dynamic SQL:
SET @sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
'sum(CASE WHEN clName = ''',
clName,
''' THEN score else ''-'' END) AS `',
clName, '`'
)
) INTO @sql
FROM clients;
SET @sql
= CONCAT('SELECT s.playdate, ', @sql, '
from clients c
inner join scores s
on c.clid = s.clid
group by s.playdate');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
See SQL Fiddle with Demo. Both queries will give the same result.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…