开发者

SQL GROUP BY - Multiple results in one column?

I am trying to perform a SELECT query using a GROUP BY clause, however I also need to access data from multiple rows and somehow concatenat开发者_如何转开发e it into a single column.

Here's what I have so far:

SELECT
COUNT(v.id) AS quantity, 
vt.name AS name, 
vt.cost AS cost, 
vt.postage_cost AS postage_cost 
FROM vouchers v 
INNER JOIN voucher_types vt 
ON v.type_id = vt.id 
WHERE 
v.order_id = 1 AND 
v.sold = 1 
GROUP BY vt.id

Which gives me the first four columns I need in the following format.

quantity | name | cost | postage_cost
2           X      5         1
2           Y      6         1

However, I would also like a fifth column to be displayed, showing all of the codes associated with each line of the order like this:

code
ABCD, EFGH
IJKL, MNOP

Where the comma separated values are pulled from the voucher table.

Is this possible? Any advice would be appreciated.

Thanks


This is what GROUP_CONCAT does.

Assuming the column is called code you would just add ,GROUP_CONCAT(v.code) As Codes to your select list.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜