我有下表'draftWorker'
select * from draftWorker;
+--------+----------+
| draftID| WorkerID |
+--------+----------+
| 7 | 8280 |
| 7 | 7794 |
| 7 | 4633 |
| 587 | 8280 |
| 587 | 4633 |
+--------+----------+
以下查询给出了以下结果。
SELECT draftID, GROUP_CONCAT(DISTINCT CONCAT(WorkerID)) AS Workers FROM
draftWorker
GROUP BY draftID;
+-----------+----------------+
| draftID | Workers |
+-----------+----------------+
| 7 | 8280,7794,4633 |
| 587 | 8280,4633 |
+-----------+----------------+
但实际上我需要这个
+-----------+---------+---------+---------+
| draftID | Worker1 | Worker2 | Worker3 |
+-----------+---------+---------+---------+
| 7 | 8280 | 7794 | 4633 |
| 587 | 8280 | 4633 | |
+-----------+---------+-------------------+
有什么想法吗?
[编辑]
还尝试了以下sql。还有很长的路要走。
SELECT draftID, Workers From (
SELECT @position := 0, draftID,
GROUP_CONCAT(DISTINCT CONCAT(WorkerID, ' As WorkerID', (@position :=
@position + 1) )) As Workers
FROM draftWorker
GROUP BY draftID) AS C;
+-----------+--------------------------------------------------------+
| draftID | Workers |
+-----------+--------------------------------------------------------+
| 7 | 8280 As WorkerID1,7794 As WorkerID2,4633 As WorkerID3 |
| 587 | 8280 As WorkerID1,4633 As WorkerID2 |
+-----------+--------------------------------------------------------+
答案 0 :(得分:1)
看看这个:
MySQL pivot row into dynamic number of columns
而且:
http://www.boynux.com/creating-pivot-reports-in-mysql/
就我所知,MySQL还没有PIVOT功能。
如果您在使用这些方法时需要任何帮助,请留下评论,我可以在有空的时候添加示例。