我一直在研究sql查询,并尝试生成一个新行,显示其下方每列的显示总和。
我现在正在接受这个
DateTime 10Quantity 20Quantity 30Quantity 10Amount 20Amount 30Amount GrandTotal
03/10/2015 792 0 594 7920 0 17820 25740
03/10/2015 332 3 194 9990 0 28220 38739
但我希望这是一个输出:
DateTime 10Quantity 20Quantity 30Quantity 10Amount 20Amount 30Amount GrandTotal
03/10/2015 792 0 594 7920 0 17820 25740
03/10/2015 332 3 194 9990 0 28220 38739
Totals 1124 3 788 17910 0 46040 64479
SP:即使我尝试过GROUPING SETS但未能实现。请帮忙。
ALTER PROCEDURE [dbo].[ReportDenominationWiseTransaction] '03-10-2015', '03-10-2015'
@FromDate date,
@ToDate date
AS
BEGIN
with myquery ([DateTime],amount,Quantity)
as
(
select Convert(varchar(20),serverdatetime,101) 'DateTime',amount,1 'Quantity'
from tickets
WHERE CONVERT(DATE,ServerDateTime) BETWEEN @FromDate and @ToDate
)
select *, 10 * c.[10Quantity] '10Amount',20 * c.[20Quantity] '20Amount',30 * c.[30Quantity] '30Amount',((10 * c.[10Quantity])+(20 * c.[20Quantity])+(30 * c.[30Quantity]))'GrandTotal' from (
SELECT DateTime,[10] AS '10Quantity', [20] AS '20Quantity', [30] AS '30Quantity'
FROM
(SELECT [DateTime], amount,quantity
FROM myquery) p
PIVOT
(
COUNT ([Quantity])
FOR [Amount] IN
( [10], [20], [30])
) AS pvt
) as c
END
答案 0 :(得分:0)
试试这个..
CREATE TABLE #tmpRes
(
DateTime varchar(50),
10Quantity varchar(50),
20Quantity varchar(50),
10Quantity varchar(50),
10Quantity varchar(50),
10Amount varchar(50),
20Amount varchar(50),
30Amount varchar(50),
GrandTotal varcahr(50)
)
INSERT INTO #tmpRes(col1,col2,....)
SELECT cols1,col2,..
FROM my_table
INSERT INTO #tmpRes(col1,col2,....)
SELECT 'Totals',sum(10Quantity ),sum(20Quantity ).......
FROM my_table
select * from #tmpRes