如何在不同月份的SQL中组合两个或三个报告?

时间:2017-04-25 20:08:39

标签: sql asp.net stored-procedures

我有一个ASPX C#应用程序,必须生成如下报告:上个月,当前月和下个月。在选择的情况下,唯一应该单独显示的是当前月,但上个月应始终与当前月和下个月组合应与上个月和当前月组合。 (希望它有意义)。

报告将打印为PDF,因此,如上所述,唯一必须单独使用的是当月(如果选择)。

有一个下拉列表,其中包含由此SQL代码填充的三个月:

SELECT  MONTH(DATEADD(month, -month, GETDATE())) AS MonthNumber,
LEFT(DATENAME(MONTH,  DATEADD(month, -month, GETDATE())), 9) AS MonthName
FROM (VALUES (1), (0), (-1)) t (month) order by MonthNumber

然后,下拉列表同时获取数值和月份名称。当用户点击三月(上个月)时,它应该打印一个三月和四月的文件。如果点击4月,只有那个月,点击5月,3月,4月和5月。

我发现的问题是如何从下拉列表中筛选所选的选项,但添加或删除相应的月份。任何更好的想法,建议或更正都将不胜感激。

这是存储过程:

ALTER PROCEDURE [dbo].[TestingWorksheet]

@MONTHSAGO int,  -- Current = 0 ; Previous = -1

AS
BEGIN
    SET NOCOUNT ON;

    IF(@MONTHSAGO = '')
    begin
        Print 'A month needs to be selected.';
    end
    ELSE

    set @MONTHSAGO = @MONTHSAGO - month(getdate()) ;

    IF (@MonthsAgo is not null)
        begin
            select HNumber, 
            dbo.InitCap(StreetIntersection) as StreetIntersection, 
                        MonthFD, 
                        '' TestDate, 
                        '' StaticPressure, 
                        '' ResidualPressure, 
                        '' FlowRestriction, 
                        '' FlushTime,
                        '' FlushRate, 
                        '' RepairNeeded, 
                        Manufacturer, 
                        '' Note
                from HMaster 
                where  testflag = 1 
                    and hsize >= 4 
                    and monthfdno = month(DATEADD(mm, @MonthsAgo, getdate()))
                order by  monthfdno

1 个答案:

答案 0 :(得分:0)

经过几个小时的分析,我能够在SQL中找到它:

if(@MonthsAgo = month(DATEADD(mm,-1, getdate())))
        begin

            select HNumber,  
                        ...
                from HMaster 
                where  testflag = 1 
                    and hsize >= 4 

                order by  monthfdno, HNumber
                end

else if(@MonthsAgo = month(getdate()))
                begin
                select HNumber, 
                ...
                from HMaster  
                where  testflag = 1 
                    and hsize >= 4 
                order by  monthfdno, HNumber
                end
else if(@MonthsAgo = month(DATEADD(mm,+1, getdate())))
                begin
                select HNumber, 
                ...

                from HMaster 
                where  testflag = 1 
                    and hsize >= 4 
                order by  monthfdno, HNumber
                end

因此,它将值:3,4,5从下拉列表传递给参数@MonthsAgo,然后将其与SQL函数month(getdate()).进行比较