2017-09-05 15 views
1

我的桌子。MySql:如何組合特定行?

 
id Exam Name isCombine 
1 Reading   0 
2 Writing   0 
3 Maths3   1 
4 Maths4   1 

上表只是一個例子。在實際表格中有更多的列。我想要合併具有合併值1的行並保留其他行。

我期待以下輸出。

 
id  Exam Name   isCombine 
1  Reading     0 
2  Writing     0 
3,4  Maths3,Maths4   1,1 

我不確定,不管它是否可能。但是,任何幫助或建議將不勝感激。

+1

你是什麼意思結合起來?你是否想要一個能讓你所有行'isCombine'爲'1'的查詢?或者究竟是什麼目的? – phaen

回答

1

你可以使用一個GROUP_CONCAT

SELECT CAST(id AS CHAR(50)) AS id, `Exam Name`, CAST(isCombine AS CHAR(50)) AS isCombine 
FROM yourTable 
WHERE isCombine = 0 
UNION ALL 
SELECT 
    GROUP_CONCAT(id), 
    GROUP_CONCAT(`Exam Name`), 
    GROUP_CONCAT(isCombine) 
FROM yourTable 
WHERE isCombine = 1 

我並沒有包括任何具體的順序,也沒有任何您指定的。如果您希望組合的行始終顯示在底部,我們可以稍微修改上述查詢以滿足此要求。

輸出:

enter image description here

演示在這裏:

Rextester

+0

非常感謝。 –