2014-11-05 84 views
0
SELECT donator, event, SUM(amount) AS total_donation_per_donator 
FROM tr_donation WHERE ngopkid=1 
GROUP BY donator, event WITH ROLLUP 

使用上述查詢我得到的結果如下。MySQL - 如何在同一查詢中使用ROLLUP和ORDER BY

Johnny Cruz 
    Charity: Event 001 | Amount: US$ 100  
    Charity: Event 002 | Amount: US$ 30  
    Charity: Event 003 | Amount: US$ 90    
         Total : US$ 220 

Mike Polo 
    Charity: Event 002 | Amount: US$ 200  
    Charity: Event 004 | Amount: US$ 125  
         Total : US$ 325 

現在我想通過數據總子每個捐贈者的分類(例如:US $ 325 US $ 220),所以用最高捐款捐贈者會首先顯示。

下面的查詢是按升序對記錄進行排序,但如果我使用'total_donation_per_donator'的DESC,它將按降序錯誤排序所有數據,結果是錯誤的。

SELECT * FROM (
    SELECT *, SUM(amount) AS total_donation_per_donator 
    FROM tr_donation 
    WHERE ngopkid=1 
    GROUP BY donator, event 
    WITH ROLLUP 
) 
temp_tr_donation ORDER BY total_donation_per_donator 

這裏是表結構。

CREATE TABLE IF NOT EXISTS `tr_donation` (
    `pkid` bigint(20) unsigned NOT NULL AUTO_INCREMENT, 
    `ngopkid` bigint(20) unsigned NOT NULL DEFAULT '0', 
    `donator` varchar(100) NOT NULL DEFAULT '', 
    `eventpkid` bigint(20) unsigned NOT NULL DEFAULT '0', 
    `event` varchar(100) NOT NULL DEFAULT '', 
    `amount` float unsigned NOT NULL DEFAULT '0', 
    `postdate` datetime DEFAULT '0000-00-00 00:00:00', 
    PRIMARY KEY (`pkid`) 
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; 
+0

http://dev.mysql.com/doc/refman/5.0/en/group-by-modifiers.html – Strawberry 2014-11-05 13:31:39

+0

是的,根據文檔,ROLLUP和ORDER BY不能一起使用。這就是爲什麼我試圖按照升序排列記錄的第二個查詢,但不是以降序排列。 – 2014-11-05 13:33:50

+0

看到您用PHP標記了這個標記,如果是我,我會簡單地返回一個排序良好的結果集並處理應用程序級別的所有彙總邏輯。 – Strawberry 2014-11-05 13:37:30

回答

1
SELECT 
    donation.`donator`, 
    donation.`event`, 
    SUM(donation.`amount`) AS total_donation_per_donator_and_event, 
    sumdonation.total_donation_per_donator 
FROM tr_donation AS donation 
INNER JOIN (
    SELECT 
     `donator`, 
     SUM(`amount`) AS total_donation_per_donator 
    FROM tr_donation 
    GROUP BY `donator` 
) AS sumdonation ON sumdonation.`donator` = donation.`donator` 
GROUP BY 
    donation.`donator`, 
    donation.`event` 
ORDER BY 
    sumdonation.total_donation_per_donator DESC, 
    donation.`event` ASC 

你應該在生產環境中使用它之前測試這個查詢與填表格。性能可能很差..

+0

謝謝,查詢給出了正確的結果,我需要在PHP中執行一些編程邏輯以正確的方式顯示數據。 – 2014-11-06 07:07:45

相關問題