日期:2014-05-17 浏览次数:20617 次
--> 测试数据:#tb
IF OBJECT_ID('TEMPDB.DBO.#tb') IS NOT NULL DROP TABLE #tb
GO
CREATE TABLE #tb([业务编号] VARCHAR(5),[币别] VARCHAR(3),[金额] NUMERIC(6,2))
INSERT #tb
SELECT 'A0001','RMB',102.00 UNION ALL
SELECT 'A0001','RMB',144.00 UNION ALL
SELECT 'A0001','RMB',103.00 UNION ALL
SELECT 'A0002','RMB',231.00 UNION ALL
SELECT 'A0002','USD',244.00 UNION ALL
SELECT 'A0002','USD',123.00 UNION ALL
SELECT 'A0003','RMB',111.00 UNION ALL
SELECT 'A0003','USD',222.00 UNION ALL
SELECT 'A0003','RMB',333.00 UNION ALL
SELECT 'A0003','USD',222.00
--------------开始查询--------------------------
SELECT [业务编号]=CASE WHEN orderid=2 THEN '小计' ELSE t.[业务编号] END ,[币别],[金额]
FROM
(
SELECT *,orderid=1 FROM #tb
UNION ALL
SELECT [业务编号],[币别],SUM([金额]),orderid=2 FROM #tb GROUP BY [业务编号],[币别]
) t
ORDER BY t.[业务编号],[币别],orderid
----------------结果----------------------------