2013-03-20 50 views
1

我有一個包含正常價格和折扣價格的MySQL數據庫。我試圖計算從這些數字的最高值到當前最低數值的百分比變化。基於兩個數字的百分比變化,未知總數(MySQL)

當正常價格低於折扣價格時,百分比不正確。

代碼:

SELECT brand_price, brand_discount_price, 
((brand_discount_price - brand_price)/brand_price) * 100 as percentage 
FROM brand 

我如何能適應的計算考慮哪一個是當前的「總」?

我想我需要改變計算或有條件地比較兩個數字的最高/最低和動態改變SELECT?有任何想法嗎?

樣本數據:

brand_price  brand_discount_price percentage 
8.7451   9.3345    6.73977427% 
7.9537   7.9538    0.00125728% 
4.5832   2.2482    -50.94693664% 
3.2331   11.8412    266.24911076% 

實施例:

品牌價格50 折扣價100

(100 - 50/50)* 100 = 100%變化

品牌價格100 折扣價50

(50 - 100/50)* 100 = -100%更改=錯誤(?)

基本上,它是由於計算完成的方式,因爲我無法弄清楚如何將總數插入總數(我認爲,百分比不是我擅長的)。如果

+1

一些樣品數據也許?? – 2013-03-20 09:53:27

+0

一些示例數據與你所得到的和你的期望... – 2013-03-20 09:54:32

+0

你希望的結果是什麼? – 2013-03-20 09:58:16

回答

3

簡單地使用(雖然我不明白爲什麼會比正常價格永遠比折一個更低):

SELECT brand_price, brand_discount_price, 
IF(brand_discount_price > brand_price, ((brand_discount_price - brand_price)/brand_discount_price) * 100, ((brand_price - brand_discount_price)/brand_price)*100) as percentage 
FROM brand 
+0

它不應該,但我想它可能會暫時發生,或者如果我比較一個新的折扣價格的歷史低價格。即使這個例子有點奇怪,我也需要這個解決方案......奇怪:)謝謝你的輸入。我會嘗試一下。 – raecer 2013-03-20 10:00:25

+0

@raecer請注意我已經做了一個更改,以反映較高的折扣價格的百分比。您在原始帖子中似乎有錯誤。 – 2013-03-20 10:03:09

2

我看到你有問題的價格和折扣的價格和比例同時,

這裏一個例子:

 $15.00  original price 
    - 1.50  - discount  // here the discount should be lower then original price. 
     $13.50  sale price 

,我在查詢猜比例要從原來的價格拿到的折扣金額的百分比。所以這將是這樣的

 SELECT round(brand_price,4) as price, round(brand_discount_price,4) as discount, 
    if(brand_discount_price < brand_price, 
    round(((brand_discount_price) * 100)/brand_price , 2), 'discount chould be less then the original price') as percentage 
     FROM `brand` 

DEMO HERE