从sql查询中检索特定数据

时间:2013-10-08 18:36:07

标签: php sql

假设我有以下查询,它给我下载和兑换的优惠券数量,按日期分组:[编辑](我无法修改此查询)[/ EDIT]

$sql = "SELECT DATE(datetime) ,
                           SUM(CASE WHEN datetime!=''  THEN 1 ELSE 0 END) As downloaded ,
                           SUM(CASE WHEN used = 1 AND DATE(datetime) != '' THEN 1 ELSE 0 END) AS redeemed

                     FROM Promotion_Redeem
                     WHERE datetime BETWEEN '2013-10-01' AND '2013-10-04'
                     GROUP BY DATE(datetime)";

如何获得下载的总和和已兑换的总和?这应该在$ sql中,某处...以下是此查询的结果:

row number 1
array (size=3)
0 => string '2013-10-01' (length=10)
1 => string '126' (length=3)
2 => string '11' (length=2)
row number 2
array (size=3)
0 => string '2013-10-02' (length=10)
1 => string '106' (length=3)
2 => string '5' (length=1)
row number 3
array (size=3)
0 => string '2013-10-03' (length=10)
1 => string '228' (length=3)
2 => string '12' (length=2)
row number 4
array (size=3)
0 => string '2013-10-04' (length=10)
1 => string '149' (length=3)
2 => string '9' (length=1)

[EDIT] bove你可以看到我得到4行,每一行都有一个数组......例如,我想要来自这些数组中每个数组的第三个字段的总和...在我的例子中,这将等于至37(即兑换的37张优惠券)[/ EDIT] 使用完之后我得到了这个数据结构:

while ($row = mysql_fetch_row($result)) {
            echo "row number ".++$i;
            var_dump($row);

        }

提前致谢

1 个答案:

答案 0 :(得分:1)

像这样修改你的php循环:

$downloaded=0;
$redeemed=0;
while ($row = mysql_fetch_row($result)) {
        echo "row number ".++$i;
        $downloaded+=$row[1];
        $redeemed+=$row[2];
        var_dump($row);
    }
echo "Downloaded: $downloaded<br>";    
echo "Redeemed: $redeemed<br>";