交叉表 mysql,在MySQL中使用交叉表查看?

I dont know I titled this correct, but let me explain what i am looking for.

I have two tables.

Clients

clID (primary key)

ClName (varchar)

Scores

ID (Primay key)

clID (F Key)

PlayDate (Date/Time)

Score (double)

Client table data looks like this

clID clName

1 Chris

2 Gale

3 Donna

Scores table data looks like this

ID clID PlayDate Score

1 2 23/01/2012 -0.0125

2 2 24/01/2012 0.1011

3 3 24/01/2012 0.0002

4 3 26/01/2012 -0.0056

5 3 27/01/2012 0.0001

6 1 12/01/2012 0.0122

7 1 13/01/2012 0.0053

Is it possible to create a view that will look like this

Date Chris Gale Donna

12/01/2012 0.0122 - -

13/01/2012 0.0053 - -

23/01/2012 - -0.0125 -

24/01/2012 - 0.1011 0.0002

26/01/2012 - - -0.0056

27/01/2012 - - 0.0001

If later there is a another new client then i should be able to check the data for that new client in the new column that will be now created in this view.

Thanks in advance.

解决方案

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;

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值