行到列(動態)我有以下表「draftWorker」MySQL的 - 使用GROUP BY(透視表)
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 |
+-----------+--------------------------------------------------------+
你真的必須在MySQL中這樣做嗎?用PHP或Python這樣的客戶端編程語言將會非常容易。 – Barmar
StackOverflow期望您[嘗試首先解決您自己的問題](http://meta.stackoverflow.com/questions/261592),並且我們也[不回答作業問題](https://softwareengineering.meta。 stackexchange.com/questions/6166)。請更新您的問題,以顯示您已經在[最小,完整和可驗證的示例]中嘗試過的內容(http://stackoverflow.com/help/mcve)。有關更多信息,請參閱[如何提出良好問題](http://stackoverflow.com/help/how-to-ask),並參加[網站之旅](http://stackoverflow.com/tour ):) – Barmar
您應該能夠在有關動態樞軸的其他問題中調整存儲過程。而不是使用表中的值作爲列名,取得最大的COUNT(*)',然後編寫一個循環,通過'Worker' –
Barmar