Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and beginning April 20th, 2021 (Eastern Time) the Yahoo Answers website will be in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.

SQL Server Procedure to sum a row by id?

Hello, I'm trying to sum rows in my database by the ItemID. Is this possible(surely it must be). I think I might be close, but it's not working the way I expected. Basically I want to be able to insert a number for the ID, then the result returns a sum of that said row(which is actually a discount price).

This is what I have so far.

CREATE PROC fnDiscountPrice

(@DiscountPrice decimal OUTPUT,

@ItemID int)

AS

BEGIN

SELECT ItemID, SUM(ItemPrice-DiscountAmount)

FROM OrderItems

GROUP BY ItemID

END

Any help would be great!

Update:

I think that it was okay, I just needed to figure out how to call it. My bad.

Update 2:

I guess not, it's still trying to sum all of the rows.

Update 3:

That did it. I was having an issue calling it and I kept taking my where clause out. Thank you for your help!

2 Answers

Relevance
  • 8 years ago

    Try this

    CREATE PROC fnDiscountPrice

    (@DiscountPrice decimal OUTPUT,

    @ItemID int)

    AS

    BEGIN

    SELECT @DiscountPrice = SUM(ItemPrice-DiscountAmount)

    FROM OrderItems

    WHERE ItemID = @ItemID

    END

  • david
    Lv 7
    8 years ago

    If I'm understanding this right, you just need to add a WHERE clause.

    Between the From and the Group By lines:

    WHERE @ItemID = ItemID

Still have questions? Get your answers by asking now.