2013-08-26 37 views
0

如何將ot_total和ot_shipping放入mysql的一行中?如何將ot_total和ot_shipping轉換爲mysql中的一行?

我想從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'); 

enter image description here

enter image description here

回答

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

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;