【解決方法】avg() 関数を使用すると、sqlite から間違った結果が得られるのはなぜですか?


I am getting wrong result from SQLite database when using avg() function!

In my database SQLITE table_name i have the following data:

Item_ID Item_name quantity price

1.     Item1      24      2.333

1.     Item2.     36      2.083

1.    Item3       24      2.25

1.    Item4       12.     2.166

1    Item5        48.     2.416

私が試したこと:

I am using this query to get average of purchase price in my project :

select sum(quantity) as Quantity, avg(price) as PRICE from table_name where item_ID=1;

The result that i expected is : 2.270416667 but I got 2.2496 instead ...
In calculator or XLS this is what I get : 2.270416667
 In calculation i do this to sum average:
(Quantity*price+Quantity*price+Quantity*price...)/Total of quantity
How can I solve the problem to get the right result?

解決策 1

結果は正しく、まさにあなたが求めていたものです。

の合計 price 列は 11.248; それを行数で割ります(5) を与える 2.2496、これはあなたが得ている結果です。

期待値を得る唯一の方法は、平均価格を取ることです アイテムごと. これを行うには、数量と価格の積を合計し、数量の合計で割る必要があります。

SQL
SELECT Sum(quantity) As Quantity, Sum(quantity * price) / Sum(quantity) As Price FROM table_name WHERE item_ID = 1;

コメント

タイトルとURLをコピーしました