日期:2014-05-17  浏览次数:20534 次

一个简单的SQL合计功能
表如下:
JO QTY
A 10
A 20
A 30
B 4
B 6
要实现如下:
JO QTY
A 10
A 20
A 30
A合计: 60
B 4
B 6  
B合计: 10
请问怎么写?

------解决方案--------------------
SQL code
--> 测试数据:[tb]
IF OBJECT_ID('[tb]') IS NOT NULL DROP TABLE [tb]
GO 
CREATE TABLE [tb]([JO] VARCHAR(1),[QTY] INT)
INSERT [tb]
SELECT 'A',10 UNION ALL
SELECT 'A',20 UNION ALL
SELECT 'A',30 UNION ALL
SELECT 'B',4 UNION ALL
SELECT 'B',6
--------------开始查询--------------------------

SELECT * FROM [tb]
UNION ALL
SELECT [JO]+'合计',SUM([QTY]) FROM tb GROUP BY [JO]+'合计'
ORDER BY [JO]
----------------结果----------------------------
/* 
JO    QTY
----- -----------
A     10
A     20
A     30
A合计   60
B     4
B     6
B合计   10
*/

------解决方案--------------------
探讨

[Quote=引用:]

不行啊,出现错误提示:
all queries in an sql statement containing a union operator must have an equal number of expressions in their target lists

------解决方案--------------------
你这是提示列数不匹配啊。