2012-09-12 38 views
2

我有一個柱(* Purchasetype *),用戶標識在視頻表purchasetype是方含一些如何值0,1,2,3,4,..等我通過userid來得到兩個和這些值的順序。MySQL查詢使用條件內部總和

對於前:sum (purchasetype) order by userid但我想這樣

if purchasetype= 0 then its value is 0.99 
if purchasetype =1 or 20 then its value is 3.99 
if purchasetype = 3 or 13or 22 then its value is 9.99 

等。下面是完整列表

0 ,17= 0.99 
1,20=3.99 
2=6.99 
3,13,22=9.99 
4,5,6,7,8,,10,11,12=0.00 
14=19.99 
15,23=39.99 
16,24=59.99 
18,21=01.99 
19=02.99 
else 
19.99 

我要總結的purchasetype所有值與他們的替代值(上面給出的)order by userid

我們可以把條件的MySQL sum()函數內;如果可能的話,請給我的解決方案,可能是這將解決我的問題

回答

3

您將使用聚合函數SUM()CASE

select 
    SUM(CASE purchaseType 
     WHEN 0 or 17 THEN 0.99 
     WHEN 1 or 20 THEN 3.99 
     WHEN 3 or 13 or 22 THEN 9.99 
     WHEN 4 or 5 or 6 or 7 or 8 or 9 or 10 or 11 or 12 THEN 0 
     WHEN 14 THEN 19.99 
     WHEN 15 or 23 THEN 39.99 
     WHEN 16 or 24 THEN 59.99 
     WHEN 18 or 21 THEN 1.99 
     WHEN 19 THEN 2.99 
     ELSE 19.99 END) as Total 
from yourTable 

看到SQL Fiddle with Demo

+0

非常感謝你的工作 – user1648175

+0

@ user1648175高興,這是工作。如果答案有幫助,那麼一定要通過左側的複選標記將其標記爲已接受。它也會幫助未來的遊客。 – Taryn

0

我認爲最好的方法是創建表ptPrices

create table ptPrices (Purchasetype int, Price float); 
insert into ptPrices values (0,0.99); 
insert into ptPrices values (1,3.99); 
.... 
insert into ptPrices values (19,2.99); 

,然後使用此查詢:

select sum(isnull(ptPrices.Price,19.99)) from Table 
left join ptPrices 
    on Table.Purchasetype=ptPrices.Purchasetype; 
0

雖然這並不MySQL查詢使用SUM,邏輯將完成這項工作

$query = mysqli_query($link, "SELECT * FROM video"); 
     while($row = mysqli_fetch_assoc($query)){ 
     //Then set conditionals 
     if($row['purchase_type)==0 || $row['purchase_type)==17){ 
       $values[] = 0.99; 
      //Then your mysqli_query here 

      } 
    elseif($row['purchase_type)==1 || $row['purchase_type)==20){ 
      $values[]= 3.99;   

      } 
    elseif//Blah blah for all values 
     } 
//After exhausting all the rows, add the SUM 
$sum = array_sum($values); //$sum will be equal to the addition of all the vlues of the //array $values