CREATE TABLE #t (
产品 varchar(2),
类型 varchar(2),
数量 INT
);
INSERT INTO #t
SELECT 'a', '1', 20 UNION ALL
SELECT 'b', '1', 30 UNION ALL
SELECT 'c', '2', 40 UNION ALL
SELECT 'd', '2', 50;
SELECT
CODE, VAL
FROM
(
SELECT
1 as Lev,
类型 as MainCode,
类型 as CODE,
SUM(数量) VAL
FROM
#t
GROUP BY
类型
UNION ALL
SELECT
2 as Lev,
类型 as MainCode,
产品 as CODE,
数量 VAL
FROM
#t
) subQuery
ORDER BY
MainCode, Lev;
查询结果:
CODE VAL
---- -----------
1 50
a 20
b 30
2 90
c 40
d 50
(6 行受影响)