MySql结果集合并列

时间:2011-11-24 09:52:06

标签: mysql resultset

我从查询中得到了这个结果集:

OrderId CustomerId  ProducerId  CustomerPayment ProducerPayment
1       1           3           10              5
1       1           4           10              5
1       2           3           10              5
1       2           4           10              5

我需要将此结果返回到:

OrderId UserId  Payment
1       1       20
1       2       20
1       3       10
1       4       10

只需将CustomerIdProducerId合并到UserId即可。与Payment列相同。

使用简单的selectgroup by有没有办法实现这一目标?我避免使用temp tables,调用多个相同的queries并进行优化。我希望这是可能的。

非常感谢

2 个答案:

答案 0 :(得分:1)

SELECT 
OrderId,
CustomerID AS UserId,
SUM (CustomerPayment) As Payment
FROM orders
UNION ALL
SELECT 
OrderId,
ProducerId AS UserId,
SUM (ProducerPayment) As Payment
FROM orders

答案 1 :(得分:0)

尝试这样的事情:

select
    OrderId,
    CustomerId,
    sum(CustomerPayment) Payment,
    group_concat(OrderId separator ',') listOrders /* list all OrderID's from the user and separates these with a , */
from your_table
group by CustomerId

不知道你的查询看起来像atm?