Попробуйте это
CREATE TABLE T
(
Branch VARCHAR(1),
SL INT,
Month VARCHAR(3),
Amount1 INT,
Amount2 INT,
Amount3 INT
);
INSERT INTO T VALUES
('A', 1, 'Jan', 10, 0, 10),
('A', 2, 'Feb', 20, 0, 20),
('B', 1, 'Jan', 5, 5, 5),
('B', 2, 'Feb', 20, 0, 20),
('C', 1, 'Jan', 55, 44, 33);
WITH CTE AS
(
SELECT *
FROM T
UNION ALL
SELECT Branch + ' SubTotal', NULL, 'SubTotal', SUM(Amount1), SUM(Amount2), SUM(Amount3)
FROM T
GROUP BY Branch
)
SELECT Branch,
SL,
Month,
Amount1,
Amount2,
Amount3
FROM CTE
ORDER BY Branch;
Результаты:
+------------+----+----------+---------+---------+---------+
| Branch | SL | Month | Amount1 | Amount2 | Amount3 |
+------------+----+----------+---------+---------+---------+
| A | 1 | Jan | 10 | 0 | 10 |
| A | 2 | Feb | 20 | 0 | 20 |
| A SubTotal | | SubTotal | 30 | 0 | 30 |
| B | 1 | Jan | 5 | 5 | 5 |
| B | 2 | Feb | 20 | 0 | 20 |
| B SubTotal | | SubTotal | 25 | 5 | 25 |
| C | 1 | Jan | 55 | 44 | 33 |
| C SubTotal | | SubTotal | 55 | 44 | 33 |
+------------+----+----------+---------+---------+---------+
Если вам действительно нужно получить Branch
и SL
пробел (''
), вы можете сделатькак
WITH CTE AS
(
SELECT Seq = Branch + 'X1',*
FROM T
UNION ALL
SELECT Branch + 'X2', '', NULL, 'SubTotal', SUM(Amount1), SUM(Amount2), SUM(Amount3)
FROM T
GROUP BY Branch
)
SELECT Branch,
SL,
Month,
Amount1,
Amount2,
Amount3
FROM CTE
ORDER BY Seq;
и результаты совпадают с вашими ожидаемыми результатами
+--------+----+----------+---------+---------+---------+
| Branch | SL | Month | Amount1 | Amount2 | Amount3 |
+--------+----+----------+---------+---------+---------+
| A | 1 | Jan | 10 | 0 | 10 |
| A | 2 | Feb | 20 | 0 | 20 |
| | | SubTotal | 30 | 0 | 30 |
| B | 1 | Jan | 5 | 5 | 5 |
| B | 2 | Feb | 20 | 0 | 20 |
| | | SubTotal | 25 | 5 | 25 |
| C | 1 | Jan | 55 | 44 | 33 |
| | | SubTotal | 55 | 44 | 33 |
+--------+----+----------+---------+---------+---------+