简体   繁体   中英

Limit sum of rows in MySQL

I want to limit the sum of product_ in columns p_description , p_reference = 1A00001 and only show rows that give us a total p_quanity <= 21000.

Here is the design of the product_table:

CREATE TABLE IF NOT EXISTS `product_table` (
  `p_id` int(11) PRIMARY KEY AUTO_INCREMENT NOT NULL,
  `p_description` varchar(50) NOT NULL,
  `p_reference` varchar(25) NOT NULL,
  `p_location` varchar(25) NOT NULL,
  `p_quantity` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

INSERT INTO `product_table` (`p_id`, `p_description`, `p_reference`, `p_location`, `p_quantity`) VALUES
(1, 'Product_1', '1A00001', 'AP07', 7000),
(2, 'Product_1', '1A00001', 'AF05', 6000),
(3, 'Product_1', '1A00233', 'DS07', 7000),
(4, 'Product_1', '1A00233', 'SD10', 5000),
(5, 'Product_1', '1A00001', 'YB12', 7000),
(6, 'Product_1', '1A00001', 'AN01', 7000),
(7, 'Product_1', '1A00001', 'AP04', 7000),
(8, 'Product_1', '1A00245', 'AP01', 7000),
(9, 'Product_1', '1A00001', 'QD01', 7000),
(10, 'Product_1', '1A00001', 'SC01', 7000);

You could try creating a running total variable, like this:

SET @runtot:=0;
SELECT p_id, p_description, (@runtot := @runtot + p_quantity) AS runningTotal
FROM product_table
WHERE @runtot + p_quantity <= 21000 AND p_reference = '1A00001';

Here is the SQL Fiddle . This will only return the first rows found that fulfill this, it doesn't return every grouping of rows that can achieve this. If all you're looking for though are any three rows that satisfy this, it should work just fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM