Вы можете myke Dynami c Запросы, так как вы никогда не знаете, какие ветки и продукты у вас будут в будущем
Схема (MySQL v8.0)
CREATE TABLE tbl_branch (
`ID` INTEGER,
`Branch_Name` VARCHAR(8)
);
INSERT INTO tbl_branch
(`ID`, `Branch_Name`)
VALUES
('1', 'Branch 1'),
('2', 'Branch 2'),
('3', 'Branch3'),
('4', 'Branch4'),
('5', 'Branch5'),
('6', 'Branch 6');
CREATE TABLE tbl_product (
`ID` INTEGER,
`Description` VARCHAR(10)
);
INSERT INTO tbl_product
(`ID`, `Description`)
VALUES
('1', 'Product 1'),
('2', 'Product2'),
('3', 'Product 3'),
('4', 'Product 4'),
('5', 'Product 5'),
('6', 'Product 6'),
('7', 'Product 7'),
('8', 'Product 8'),
('9', 'Product 9'),
('10', 'Product 10');
CREATE TABLE tbl_orders (
`ID` INTEGER,
`Branch_ID` INTEGER,
`Item_ID` INTEGER,
`Qty` INTEGER
);
INSERT INTO tbl_orders
(`ID`, `Branch_ID`, `Item_ID`, `Qty`)
VALUES
('1', '1', '1', '12'),
('2', '1', '2', '3'),
('3', '2', '3', '4'),
('4', '3', '4', '5'),
('5', '3', '1', '67'),
('6', '4', '1', '1'),
('7', '5', '2', '1'),
('8', '1', '3', '1'),
('9', '1', '4', '2'),
('10', '6', '5', '3');
Запрос №1
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
'SUM(CASE o.`Branch_ID` WHEN "',
o.`Branch_ID`,
'" THEN o.`Qty` ELSE 0 END) AS `',
b.`Branch_Name`, '`'
)
ORDER BY o.`Branch_ID`
)
INTO @sql
FROM tbl_product as p
JOIN tbl_orders as o on p.ID = o.Item_ID
JOIN tbl_branch as b on o.Branch_ID = b.ID;
SET @sql = CONCAT('SELECT p.Description as item,',@sql,
', SUM(o.Qty) as `Total Qty` FROM tbl_product as p
JOIN tbl_orders as o on p.ID = o.Item_ID
JOIN tbl_branch as b on o.Branch_ID = b.ID GROUP BY p.id,p.Description;');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
| item | Branch 1 | Branch 2 | Branch3 | Branch4 | Branch5 | Branch 6 | Total Qty |
| --------- | -------- | -------- | ------- | ------- | ------- | -------- | --------- |
| Product 1 | 12 | 0 | 67 | 1 | 0 | 0 | 80 |
| Product2 | 3 | 0 | 0 | 0 | 1 | 0 | 4 |
| Product 3 | 1 | 4 | 0 | 0 | 0 | 0 | 5 |
| Product 4 | 2 | 0 | 5 | 0 | 0 | 0 | 7 |
| Product 5 | 0 | 0 | 0 | 0 | 0 | 3 | 3 |
Просмотр в DB Fiddle