Calculate TotalAmount from all Rows in Table

[亡魂溺海] 提交于 2019-12-11 05:48:32

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!