0

如何在 mysql 中将 ot_total 和 ot_shipping 放入一行?

我想从 ot 表收取每个订单的费用。我怎样才能在mysql中得到这个表呢?
非常感谢您。

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for `ot`
-- ----------------------------
DROP TABLE IF EXISTS `ot`;
CREATE TABLE `ot` (
  `id` int(10) NOT NULL auto_increment,
  `orders_id` int(10) default NULL,
  `class` varchar(30) default NULL,
  `value` float(30,0) default NULL,
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of ot
-- ----------------------------
INSERT INTO `ot` VALUES ('1', '1', 'ot_shipping', '10');
INSERT INTO `ot` VALUES ('2', '1', 'ot_total', '100');
INSERT INTO `ot` VALUES ('3', '1', 'ot_insurance', '1');
INSERT INTO `ot` VALUES ('4', '2', 'ot_shipping', '10');
INSERT INTO `ot` VALUES ('5', '2', 'ot_total', '80');

在此处输入图像描述

在此处输入图像描述

4

2 回答 2

1
select orders_id, 
       sum(case when class='ot_shipping' then value else 0 end) as shipping,
       sum(case when class='ot_total' then value else 0 end) as total
from ot
GROUP BY orders_id;

SqlFiddle

于 2013-08-26T06:50:56.430 回答
1
select o.orders_id, 
       sum(case when o.class='ot_shipping' then o.value else 0 end) as ot_shipping,
       sum(case when o.class='ot_total' then o.value else 0 end) as ot_total
from ot o
GROUP BY o.orders_id;
于 2013-08-26T06:54:49.183 回答