我有一个以下存储过程,它完美地工作但需要在行尾的水平总计,例如THE FOLLOWING ..它应该在每一行...
[1] [2]。[3] .................. ............ [29]。[30]。[31] ... TOTAL
..请帮忙
CREATE PROCEDURE [dbo].[VTR_Report_DaysOfMonthWise]
@Month int,
@Year int,
@Branch_ID int
AS
BEGIN
DECLARE @startDate varchar(20)
DECLARE @endDate varchar(20)
SELECT @startDate = Convert(varchar(10),DATEADD(m, @Month - 1, DATEADD(yyyy, @Year - 1900, 0)),105)
SELECT @endDate = Convert(varchar(10),DATEADD(d, -1, DATEADD(m, @Month, DATEADD(yyyy, @Year - 1900, 0))),105)
SELECT *
FROM
(
SELECT c.CLName, DATEPART(dd,cd.vtrRespDate) as 'Day', ISNULL(sum(cast(cd.vtrvalue as int)),0) as 'VTRValue'
FROM dbo.VTRCheckList c
LEFT OUTER JOIN VTRCheckListDetails cd ON cd.CLid = c.CLid
AND Convert(date,cd.vtrRespDate, 105) >= convert(date,@startDate,105) and Convert(date, cd.vtrRespDate, 105) <= convert(date,@endDate,105)
AND cd.branchid = @Branch_ID
GROUP BY c.CLName, DATEPART(dd,cd.vtrRespDate)
) a
PIVOT
(
SUM(VTRValue) FOR Day IN
(
[1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12], [13], [14], [15],
[16], [17], [18], [19], [20], [21], [22], [23], [24], [25], [26], [27], [28], [29],
[30], [31]
)
) b
END
答案 0 :(得分:0)
在内部查询中添加一个子查询,将月份的总和拉为单独的列,如下所示,子查询col命名为MonthTotal。 (我假设vtrRespDate是一个日期字段。)
SELECT c.CLName,
DATEPART(dd,cd.vtrRespDate) as 'Day',
ISNULL(sum(cast(cd.vtrvalue as int)),0) as 'VTRValue',
(SELECT ISNULL(sum(cast(x.vtrvalue as int)),0)
FROM VTRCheckListDetails x
WHERE YEAR(x.vtrRespDate) = YEAR(cd.vtrRespDate)
AND MONTH(x.vtrRespDate) = MONTH(cd.vtrRespDate)
AND Convert(date,cd.vtrRespDate, 105) >= convert(date,@startDate,105)
AND Convert(date, cd.vtrRespDate, 105) <= convert(date,@endDate,105)) as MonthTotal
FROM dbo.VTRCheckList c
LEFT JOIN VTRCheckListDetails cd ON cd.CLid = c.CLid
AND Convert(date,cd.vtrRespDate, 105) >= convert(date,@startDate,105)
AND Convert(date, cd.vtrRespDate, 105) <= convert(date,@endDate,105)
AND cd.branchid = @Branch_ID
GROUP BY c.CLName, DATEPART(dd,cd.vtrRespDate)
答案 1 :(得分:0)
我只是尝试了这个并且像魅力一样工作:) ..粘贴在这里,所以别人可以从中受益......真是太容易了。
SELECT
*
,[1] + [2] + [3] + [4] + [5] + [6] + [7] + [8] + [9] + [10] + [11] + [12] + [13] + [14] + [15] +
[16] + [17] + [18] + [19] + [20] + [21] + [22] + [23] + [24] + [25] + [26] + [27] + [28] + [29] +
[30] + [31] AS Total
FROM
(
SELECT c.CLName, DATEPART(dd,cd.vtrRespDate) as 'Day', ISNULL(sum(cast(cd.vtrvalue as int)),0) as 'VTRValue'
FROM dbo.VTRCheckList c
LEFT OUTER JOIN VTRCheckListDetails cd ON cd.CLid = c.CLid
AND Convert(date,cd.vtrRespDate, 105) >= convert(date,@startDate,105) and Convert(date, cd.vtrRespDate, 105) <= convert(date,@endDate,105)
AND cd.branchid = @Branch_ID
GROUP BY c.CLName, DATEPART(dd,cd.vtrRespDate)
) a
PIVOT
(
SUM(VTRValue) FOR Day IN
(
[1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12], [13], [14], [15],
[16], [17], [18], [19], [20], [21], [22], [23], [24], [25], [26], [27], [28], [29],
[30], [31]
)
) b