mysql使用group by获取行值

时间:2016-03-28 14:13:38

标签: php mysql

id order_id coupon_code coupon_amount
1   100        abc123    50
2   101        abc123    50
3   102        bca412    100

我的查询是

 SELECT `coupon_code`, `order_id`, 
        SUM(`coupon_amount`) AS `total`, 
        COUNT(`id`) as `totRow` 
 FROM `orders` 
 WHERE `coupon_code`!='' 
 GROUP BY `coupon_code`

我的输出应该是

coupon code  Usage  Total  Order Id(s)
abc123         2    100    100, 101
bca412         1    100    102

如何在单个查询中以逗​​号分隔所有订单ID?

谢谢

1 个答案:

答案 0 :(得分:2)

您可以使用GROUP_CONCAT

SELECT `coupon_code`, 
       GROUP_CONCAT(`order_id`) as order_ids, 
       SUM(`coupon_amount`) AS `total`, 
       COUNT(`id`) as `totRow` 
FROM `orders` 
WHERE `coupon_code`!='' 
GROUP BY `coupon_code`