2

我有一个列(* Purchasetype *),视频表purchasetype中的用户 ID是如何包含值 0,1,2,3,4,.. 等的。我想要两个将这些值按顺序相加userid

例如: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

我们可以把条件放在sum()mysql的函数里面吗?如果可能的话,请给我解决方案,也许这会解决我的问题

4

3 回答 3

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

于 2012-09-12T11:30:55.863 回答
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
于 2012-09-12T11:38:48.450 回答
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;
于 2012-09-12T11:37:11.273 回答