简体   繁体   中英

Group by date in SQL stored procedure to calulate revenue

I'm trying to group revenue by invoice date but it doesn't seem to work. Please guide me what I am missing here

My stored procedure:

ALTER PROCEDURE GetRevenueDaily 
    @fromDate VARCHAR(10),
    @toDate VARCHAR(10)
AS
BEGIN
    SELECT 
        CAST(b.create_at AS DATE) AS Date,
        SUM(b.total + b.transport_fee - b.discount) AS Revenue
    FROM 
        Bill b
    WHERE 
        b.create_at <= CAST(@toDate AS Date)
        AND b.create_at >= CAST(@fromDate AS Date)
        AND b.status = 1
        AND b.isPay = 1
    GROUP BY 
        b.create_at
END

EXEC dbo.GetRevenueDaily @fromDate = '07/02/2021',
                         @toDate = '07/30/2021'

I'm trying use group by b.create_at but it doesn't work :(

RESULT:

2021-07-04  1499000.00
2021-07-04  21699000.00
2021-07-04  3199000.00
2021-07-04  32180000.00
2021-07-05  40888000.00
2021-07-05  23394000.00
2021-07-05  4299000.00
2021-07-05  7299000.00
2021-07-05  5299000.00
2021-07-15  4399000.00
2021-07-15  22899000.00
2021-07-15  47957000.00
2021-07-16  4299000.00
2021-07-17  5086400.00
2021-07-18  4399000.00
2021-07-24  114995000.00
2021-07-25  1619000.00

Use the correct data types! If the stored procedure wants dates, then pass them in as dates:

ALTER PROC GetRevenueDaily (
    @fromDate DATE,
    @toDate DATE
) AS
BEGIN
    SELECT CAST(b.create_at as DATE) as Date,
           SUM(b.total + b.transport_fee - b.discount) as Revenue
   FROM Bill b
   WHERE b.create_at <= @toDate AND
         b.create_at >= @fromDate AND
         b.status = 1 AND
         b.isPay = 1
   GROUP BY CAST(b.create_at as DATE);
------------^ Note that this is also fixed to match the `SELECT`
END;

I don't know how the data is stored, but this line could be troublesome if there are NULL values:

SUM(b.total + b.transport_fee - b.discount) 

You may want:

SUM(COALESCE(b.total, 0) + COALESCE(b.transport_fee, 0) - COALESCE(b.discount, 0)) 

When you call the stored procedure, use canonical date formats

EXEC dbo.GetRevenueDaily @fromDate = '2021-07-02',
                         @toDate = '2021-07-30';

Note: You might also consider writing this stored procedure as a stored function so you can use the results in a SELECT .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM