MYSQL SUM over QTY and values

I would like to know if it is possible to get two sums from one query using table values ​​and then add them togther.

Here are some simple tables and data that might help.

    CREATE TABLE `cartcontents` (
  `id` int(11) NOT NULL auto_increment,
  `code` varchar(40) NOT NULL,
  `qty` int(10) NOT NULL,
  `price` decimal(30,2) NOT NULL,
  `cart_id` int(11) NOT NULL,
  PRIMARY KEY  (`id`),
  UNIQUE KEY `zone` (`zone_code`,`cart_id`)
) ENGINE=MyISAM AUTO_INCREMENT=8 DEFAULT CHARSET=latin1;

-- ----------------------------
-- Records 
-- ----------------------------
INSERT INTO `cartcontents` VALUES ('5', '011242077783866125432', '1', '36.00', '2');
INSERT INTO `cartcontents` VALUES ('4', '011242077793513596890', '3', '33.00', '4');
INSERT INTO `cartcontents` VALUES ('6', '011242077649557011493', '1', '110.00', '4');
INSERT INTO `cartcontents` VALUES ('7', '011242077724922511037', '1', '177.00', '5');

      

So, I would like to get the total and total for a given cart_id.

So, this would mean that if I had 3 in qty, the sum would have to be (qty * price) for each zone, then add them in total for cart_id.

So in the example above, if I was looking for values ​​for cart_id 4 The values ​​I could hope for could be qty = 4 and total value = 209

Hope this makes sense and thanks if you can help.

0


a source to share


1 answer


Something like this should work:



SELECT SUM(qty) AS qty, SUM(qty * price) AS total
FROM cartcontents
GROUP BY cart_id

      

+3


a source







All Articles