2016-07-28 62 views
1

我有一個用戶一個MySQL表預算:在MySQL的加入行有類似值的

+--------+-----------+----------+----------+ 
| req_id | name  | id_2  | budget | 
+--------+-----------+----------+----------+ 
| 1  | User1  | 9  | 10  | 
| 1  | User2  | 9  | 100  | 
| 1  | User3  | 9  | 1000  | 
| 1  | User4  | 9  | 10000 | 
| 2  | User1  | 4  | 5  | 
| 2  | User2  | 4  | 50  | 
| 2  | User3  | 4  | 500  | 
| 2  | User4  | 4  | 5000  | 
+--------+-----------+----------+----------+ 

那種觀點我想:

+--------+-----------+----------+----------+----------+----------+ 
| req_id | id_2  | User1 | User2 | User3 | User4 | 
+--------+-----------+----------+----------+----------+----------+ 
| 1  | 9   | 10  | 100  | 1000  | 10000 | 
| 1  | 4   | 5  | 50  | 500  | 5000  | 
+--------+-----------+----------+----------+----------+----------+ 

我使用的查詢:

SET @sql = NULL; 
SELECT 
GROUP_CONCAT(DISTINCT 
    CONCAT(
    'IF(`name` = ''', `name`, ''',budget,0) AS ', `name`) 
    ) INTO @sql 
    FROM myTable; 

SET @sql = CONCAT('SELECT req_id, id_2', 
       @sql, 
       ' FROM myTable 
       group by req_id, id_2, name 
       order by req_id, id_2, name'); 

PREPARE stmt FROM @sql; 
EXECUTE stmt; 
DEALLOCATE PREPARE stmt; 

這就是我到目前爲止所取得的成果:

+--------+-----------+----------+----------+----------+----------+ 
| req_id | id_2  | User1 | User2 | User3 | User4 | 
+--------+-----------+----------+----------+----------+----------+ 
| 1  | 9   | 10  | 0  | 0  | 0  | 
| 1  | 9   | 0  | 100  | 0  | 0  | 
| 1  | 9   | 0  | 0  | 1000  | 0  | 
| 1  | 9   | 0  | 0  | 0  | 10000 | 
| 1  | 4   | 5  | 0  | 0  | 0  | 
| 1  | 4   | 0  | 50  | 0  | 0  | 
| 1  | 4   | 0  | 0  | 500  | 0  | 
| 1  | 4   | 0  | 0  | 0  | 5000  | 
+--------+-----------+----------+----------+----------+----------+ 

所以我的問題是,我如何獲得在不同值的同一行中的答案?

非常感謝!

+0

更好的分享** sql小提琴**。 – 1000111

回答

0

試試這個請:

SET @sql = NULL; 
SELECT 
GROUP_CONCAT(DISTINCT 
    CONCAT(
    'MAX(IF(`name` = ''', `name`, ''',budget,0)) AS ', `name`) 
    ) INTO @sql 
    FROM myTable; 

SET @sql = CONCAT('SELECT req_id, id_2,', 
       @sql, 
       ' FROM myTable 
       group by req_id 
       order by req_id, id_2, name'); 

PREPARE stmt FROM @sql; 
EXECUTE stmt; 
DEALLOCATE PREPARE stmt; 

變化:

1) MAX(IF(`name` = ''', `name`, ''',budget,0)) AS ', `name`) 

2) You needed to group by `req_id` only. 

看到一個*WORKING DEMO

*您需要向下滾動查看輸出