Mysql:基于原因,历史状态和当前状态的订单计数

时间:2013-05-08 12:32:25

标签: mysql sql

我想根据历史状况和原因计算订单数量和收入总和。

以下是我的表结构。

订单表: -

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. 订单的状态为“欺诈” (在这种情况下需要仅检查当前状态。) ......
  4. 如何根据上面定义的存储桶获取计数或订单以及收入。 我在计算第3点和第4点的订单时遇到问题,并在单个查询中获得所有计数。

1 个答案:

答案 0 :(得分: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.