我想根据历史状况和原因计算订单数量和收入总和。
以下是我的表结构。
订单表: -
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 ;
我需要将订单分组到以下存储桶中,
如何根据上面定义的存储桶获取计数或订单以及收入。 我在计算第3点和第4点的订单时遇到问题,并在单个查询中获得所有计数。
答案 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.