我在使用以下表格在MySQL中创建数据透视表时遇到了问题:
Tasks
----------
taskid | taskdesc
1 | GenOP
2 | Forks
3 | Carpenter
4 | Brickie
5 | Digger
6 | Plaster
7 | Sparks
8 | Trucks
9 | Warehouse
10 | CrewBoss
Clients
-------
clientid|clientname
1 | Client 1
2 | Client 2
3 | Client 3
4 | Client 4
Clienttaskrates
--------------------
rateid|clientid|taskid|rate
1 | 1 | 1 | 10
2 | 1 | 2 | 12
3 | 3 | 2 | 12
4 | 3 | 3 | 14
5 | 3 | 4 | 12
6 | 4 | 4 | 18
7 | 1 | 5 | 18
8 | 2 | 1 | 13
9 | 2 | 2 | 13
10 | 2 | 3 | 13
我正在使用此存储过程来生成表:
BEGIN
SET @@group_concat_max_len = 32000;
SET @sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
'MAX(IF(rate = ',
rate,
', rate, NULL)) AS ',
replace(taskdesc, ' ', '')
)
) INTO @sql
from tasks pd JOIN clienttaskrates s ON pd.taskid=s.taskid;
SET @sql = CONCAT('SELECT pt.clientname, ', @sql, ' from clienttaskrates s
left join clients pt
on s.clientid=pt.clientid
left join tasks pd
on s.taskid = pd.taskid
group by pt.clientname');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END
我收到了错误的结果和重复的列,这里可以看到http://sqlfiddle.com/#!9/1bba1/4
对于每个任务应该只有列,并且似乎存在不应该存在某些行的值(客户端1具有'12'值,而brickie和brickie出现两次)。
我认为这是我的JOINS的一个问题,但我尝试了几个不同的事情无济于事。任何帮助都会很棒,谢谢!