简体   繁体   中英

Adding values returned by SQL query to get the total?

I have a function that gets the Quantity and Weight of each item for a user's order from a SQL table based on the order id:

protected decimal getOrderWeight(int orderid)
{
    string sqlCmd = "SELECT Weight, Quantity FROM OrderItems WHERE OrderId = @OrderId";
    int qty = 0;
    decimal wgt = 0;
    decimal totalWeight = 0;
    using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["AbleCommerce"].ToString()))
    {
        cn.Open();
        SqlCommand cmd = new SqlCommand(sqlCmd, cn);
        cmd.Parameters.AddWithValue("@OrderId", orderid);
        using (IDataReader reader = cmd.ExecuteReader())
        {
            while (reader.Read())
            {
                qty = Convert.ToInt32(reader["Quantity"]);
                wgt = Convert.ToDecimal(reader["Weight"]);     
                totalWeight = qty * wgt;
            }
            cn.Close();
        }
    }
    return totalWeight;
}

In the table (which is called OrderItems), each item has a quantity and a weight. However, the weight featured in the table is NOT the result of weight * quantity (ie item ABC has a quantity of 6 for Order #12345, and each ABC item weighs 1.00 lbs.). The function I created works in that it multiplies each order item's quantity by the weight (ie The total weight for all 6 ABC items is 6.00 lbs)

However, I now need to take these total weight values and add them together to get the total weight for the whole order. Right now, I am returning all the weights in an order: 6.00, 5.00, 2.80, 146.76, 6.02, 2.25

But I am not sure how to add all these together? I was thinking of doing a Split() but then I would be converting decimals to strings only to convert them back to decimals to add them together once "split." This seems awfully complicated...is there a better way?

Is this what you are looking for?

SELECT sum(Weight * Quantity) as TotalWeight
FROM OrderItems
WHERE OrderId = @OrderId;

If so, this is an example of an aggregation query, which is a basic SQL concept. You should do this type of work in the database, because the database is optimized to work with large volumes of data and extract such results from the tables.

Shouldn't you sum total weight values like this: totalWeight += qty * wgt;

Because now your totalWeight will contain total weight value of last item in order only.

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