将每个选定的行乘以某个值,然后将单个查询中的所有内容相加

时间:2018-07-22 19:57:51

标签: mysql sql

我有一张桌子,看起来像这样:

enter image description here

我想计算100位成人和20位儿童的门票总价。我不知道如何添加多个WHERE以选择正确的行进行计算。到目前为止,我有类似的东西

SELECT
  Fee * 100 AS adult,
  Fee * 20  AS child,
  sum(*)
FROM fees
WHERE adult.Type = 'adult' AND adult.Clubname = 'aquapark'
WHERE child.Type = 'child' AND child.Clubname = 'aquapark';

在这种情况下,我希望输出为11万。

谢谢您的帮助!

3 个答案:

答案 0 :(得分:3)

听起来像您可以使用条件聚合。

<div>      <!-- Added by edit -->
  <div>    <!-- Added by edit -->

<?php


require_once 'dbconfig.php';

if(isset($_GET['id']) && !empty($_GET['id']))
{
	$id = $_GET['id'];
	$stmt = $DB_con->prepare('SELECT productid,productname,availablesize FROM products WHERE productid=:uid');
	
	$stmt->execute(array(':uid'=>$id));
	$row = $stmt->fetch(PDO::FETCH_ASSOC);
	extract($row);
	
}
else
{
	header("Location: index.php");
}
 

?>
    <input type="radio" id="red" name="requiresize" value="<?php echo $availablesize;?>" checked>
    <label for="red"><span class="sizespan"><?php echo $availablesize;?></span></label>
  </div>
  <div>
    <input  type="radio" id="blue" name="requiresize"  value="<?php echo $availablesize;?>">
    <label for="blue"><span class="sizespan"><?php echo $availablesize;?></span></label>
  </div>
  <div>
    <input  type="radio" id="black" name="requiresize" value="<?php echo $availablesize;?>">
    <label for="black"><span class="sizespan"><?php echo $availablesize;?></span></label>
  </div>
  <div>
    <input  type="radio" id="black" name="requiresize" value="<?php echo $availablesize;?>">
    <label for="black"><span class="sizespan"><?php echo $availablesize;?></span></label>
  </div>
</div>

答案 1 :(得分:2)

    SELECT  SUM(totalAmount) totalAmount
    FROM
        ( 
            select sum(fees.fee * 200) totalAmount from fees where fees.Type = 'adult' AND fees.Clubname = 'aquapark'
            UNION ALL
            select sum(fees.fee * 50) totalAmount from fees where fees.Type = 'child' AND fees.Clubname = 'aquapark'
        ) s

上面的查询是对成人和儿童进行的单独查询的总和,假设您想要特定俱乐部名称的结果,并且您的列名和表名正确。

答案 2 :(得分:1)

您应该使用

SUM(fee)
WHERE Type IN ('child', 'adult')
GROUP BY(Clubname, Type)

得到想要的东西。