2011-11-24 70 views
0

我有這樣的結果,從我的查詢設置:的MySQL結果集組合列

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 

只是結合CustomerIdProducerIdUserId。與Payment列相同。

有什麼辦法可以通過簡單的使用selectgroup by來實現嗎?我在迴避temp tables,呼籲多重queries等優化。我希望這是可能的。

非常感謝

+0

您將需要對數據進行規範化處理,以實現您要查找的內容。打破客戶,客戶支付作爲一個記錄,並將產品和生產者支付作爲另一個記錄 – ajreal

+0

謝謝,但我怎麼能打破它們?第一個表格已經是查詢結果。只需要操縱它們。 – KaeL

+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 
+0

所以有沒有其他的方式,但這?我在想如果我只能從查詢中調用'orders'一次。在你的答案之後將屈服於兩次調用相同的查詢。謝謝BTW – KaeL

+2

你不忘記group by子句嗎? – Fred

+0

是的,我忘了它,不能編輯帖子atm –

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?

+0

有沒有列作爲userid – ajreal

+0

即將這樣說:D – KaeL

+0

哈哈,改變它:P –