Calculating the SUM of (Quantity*Price) from 2 different tables

前端 未结 5 1838
孤独总比滥情好
孤独总比滥情好 2021-02-04 15:45

I have two tables as follows

PRODUCT table

Id | Name | Price

And an ORDERITEM table

Id | Orde         


        
5条回答
  •  我寻月下人不归
    2021-02-04 16:29

    I had the same problem as Marko and come across a solution like this:

    /*Create a Table*/
    CREATE TABLE tableGrandTotal
    (
    columnGrandtotal int
    )
    
    /*Create a Stored Procedure*/
    CREATE PROCEDURE GetGrandTotal
    AS
    
    /*Delete the 'tableGrandTotal' table for another usage of the stored procedure*/
    DROP TABLE tableGrandTotal
    
    /*Create a new Table which will include just one column*/
    CREATE TABLE tableGrandTotal
    (
    columnGrandtotal int
    )
    
    /*Insert the query which returns subtotal for each orderitem row into tableGrandTotal*/
    INSERT INTO tableGrandTotal
        SELECT oi.Quantity * p.Price AS columnGrandTotal
            FROM OrderItem oi
            JOIN Product p ON oi.Id = p.Id
    
    /*And return the sum of columnGrandTotal from the newly created table*/    
    SELECT SUM(columnGrandTotal) as [Grand Total]
        FROM tableGrandTotal
    

    And just simply use the GetGrandTotal Stored Procedure to retrieve the Grand Total :)

    EXEC GetGrandTotal
    

提交回复
热议问题