在给定的月份和年份中,客户花在书上的SQL总金额

时间:2020-04-16 15:10:16

标签: stored-procedures

我对SQL还很陌生,并且一直在尝试创建一个存储过程,该存储过程允许用户输入月份(int)和年份(int)作为参数,然后在此过程中显示CustomerNumber,CustomerName和TotalAmountSpent给定的月份和年份。我遇到的问题是执行程序时,它没有显示每个客户的实际SUM。它显示了多个完全相同的客户编号和客户名称,并列出了他们在该时间段内花费的所有单独金额。它应该仅显示每个客户一个结果并具有实际的总和。我将提供您的代码供您查看,任何帮助将不胜感激!我很确定这只是SELECT语句是不正确的,因为我的错误行以及有关SPROC的所有其他内容似乎都在按应有的方式运行。

    CREATE PROCEDURE CustomerBooks
    @SaleMonth          int,
    @SaleYear           int
AS

    IF @SaleMonth IS NULL OR @SaleYear IS NULL
    BEGIN
        RAISERROR('You must enter the desired month and year to display the customer sale information', 16, 1)
    END
    ELSE
    BEGIN
        IF @SaleMonth < 1 OR @SaleMonth > 12
        BEGIN
            RAISERROR ('That Sale Month is not valid', 16, 1)
        END
        ELSE
        BEGIN
            IF @SaleMonth > MONTH(GETDATE())
            BEGIN
                RAISERROR ('That Sale Month is in the future', 16, 1)
            END
            ELSE
            BEGIN
                IF @SaleYear > YEAR(GETDATE())
                BEGIN
                    RAISERROR ('That Sale Year is in the future', 16, 1)
                END
                ELSE
                BEGIN
                    SELECT C.CustomerNumber AS 'Customer Number', LastName + ', ' + FirstName AS 'CustomerName', SUM(Subtotal) AS 'Total Amount Spent'
                    FROM Customers C
                        INNER JOIN Sales S ON S.CustomerNumber = C.CustomerNumber
                        GROUP BY Date, C.CustomerNumber, LastName, FirstName
                        HAVING Month(Date) = @SaleMonth AND YEAR(Date) = @SaleYear                      
                END
            END
        END
    END
RETURN
GO

这也是执行该过程时我在表中得到的结果的图片: https://drive.google.com/file/d/1g5V3ojT1K-U5LCdK-KftxHgRfdi8NhNU/view?usp=sharing

0 个答案:

没有答案