2013-05-08 39 views
1

我想根據歷史狀態和原因計算訂單的計數和收入的總和。Mysql:基於原因,歷史狀態和當前狀態的訂單計數

以下是我的表格結構。

順序表: -

CREATE TABLE `order_item` (
    `id_order_item` int(10) unsigned NOT NULL AUTO_INCREMENT, 
    `unit_price` decimal(17,2) DEFAULT NULL, 
    `fk_reason` int(11) DEFAULT NULL, 
    PRIMARY KEY (`id_order_item`), 
    KEY `fk_reason` (`fk_reason`) 
) ENGINE=InnoDB; 

歷史表: -

CREATE TABLE `order_item_status_history` (
    `id_order_item_status_history` int(10) unsigned NOT NULL AUTO_INCREMENT, 
    `fk_order_item` int(10) unsigned NOT NULL, 
    `fk_order_item_status` int(10) unsigned NOT NULL COMMENT ''New status'', 
    `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, 
    `created_at` datetime DEFAULT NULL, 
    PRIMARY KEY (`id_order_item_status_history`), 
    KEY `fk_order_item` (`fk_order_item`), 
    CONSTRAINT `order_item_status_history_ibfk_1` FOREIGN KEY (`fk_order_item`) REFERENCES `order_item` (`id_order_item`) ON DELETE CASCADE ON UPDATE NO ACTION, 
    CONSTRAINT `order_item_status_history_ibfk_3` FOREIGN KEY (`fk_order_item_status`) REFERENCES `order_item_status` (`id_order_item_status`) ON DELETE NO ACTION ON UPDATE NO ACTION 
) ENGINE=InnoDB; 

狀態表: -

CREATE TABLE `order_item_status` (
    `id_order_item_status` int(10) unsigned NOT NULL, 
    `name` varchar(50) NOT NULL, 
    `desc` varchar(255) NOT NULL, 
    `deprecated` tinyint(1) DEFAULT ''0'', 
    PRIMARY KEY (`id_order_item_status`), 
) ENGINE=InnoDB; 

原因表: -

CREATE TABLE `reason` (
    `id_reason` int(10) unsigned NOT NULL AUTO_INCREMENT, 
    `name` varchar(100) NOT NULL, 
    `desc` varchar(255) NOT NULL, 
    PRIMARY KEY (`id_cancel_reason`), 
) ENGINE=InnoDB ; 

我需要組訂單到下面的水桶,

  1. 訂單具有地位的「封閉」,如果訂單已發貨之前(即。是「運」)
  2. 訂單的順序 以前的狀態具有狀態爲「關閉」。如果訂單不是之前的順序(即以前的狀態不是「運」) 運(在這種情況下,需要檢查當前狀態還有的爲了以前的狀態。)
  3. 訂單具有狀態爲「欺詐」 (在這種情況下,只需要查看當前狀態。) ......

如何我可以得到計數或訂單,並有收入以上定義的桶。 我在計算點3和點4的訂單時遇到問題,並在單個查詢中獲得所有計數。

+0

這真的很難理解你的問題。如果你能顯示你已經嘗試了什麼,以及一些樣本數據和期望的結果,這將有所幫助。哦,點4. – fancyPants 2013-05-09 08:10:29

回答

1

要獲得所有這些到一個查詢時,您需要具體的幫助,您可以使用CASE WHEN ..這樣

SELECT 
whateverYouAreGroupingByIfNeeded, 
SUM(CASE WHEN status = 'canceled' AND reason = 1 THEN 1 ELSE 0 END) AS count_whatever 
SUM(CASE WHEN whatever = true THEN whateverYouWantToSummarize ELSE NULL END) AS sum_whatever 
FROM yourTable 
GROUP BY whatever 

,這是最好的證明,你已經嘗試過的東西。

P.S:如果您有任何關於加盟麻煩,閱讀this.

+0

我沒有連接問題,我可以得到1點和2點的計數我的問題是在3點和4點,並結合這一切統計的結果。 – 2013-05-08 13:01:43