问题
Can you please help me with this? I am trying to calculate the total of all the rows in my Price Table, but the values never add up, and now it doesn't seem to calculate anymore either.
I have the following:
@{
decimal money = 0.00m;
var prices = "SELECT Price, SUM(Price) FROM PriceTable GROUP BY Price";
var database = Database.Open("MYDB");
database.QuerySingle(prices);
money = prices.AsDecimal();
}
And somewhere in my HTML I type:
@money // to display the totalAmount
Am I doing it right? I've searched for this, but surprisingly there seems to be not much info about this, I'm probably not using the right keywords though.
Thank you
回答1:
change
var prices = "SELECT Price, SUM(Price) FROM PriceTable GROUP BY Price";
to
var prices = "SELECT SUM(Price) FROM PriceTable";
IF all you want is the sum of all rows, the grouping is not required.
Also;
var result = database.QuerySingle(prices);
money = Convert.ToDecimal(result);
回答2:
That's because you add the price itself too. You sum only the distinct prices, so for every price that is unique, the sum is the same as the price.
To be short: Remove the price and the group by. Just query sum(price) over the whole table.
回答3:
{@money}
<-- isn't this the correct syntax? not "@money" only if I remember correctly...
and also the comments below with the query! =]
来源:https://stackoverflow.com/questions/6514059/calculate-totalamount-from-all-rows-in-table