我有一张如下图所示的表格。如何在 type=1 AND type=2 的地方选择 SUM 列价格?我想在一个查询中获取 type=1 的总价格和 type=2 的总价格。
+-----+------+-------+
| PID | Type | Price |
+-----+------+-------+
| 1 | 1 | 100 |
| 2 | 2 | 65 |
| 3 | 1 | 300 |
| 4 | 1 | 200 |
| 5 | 2 | 50 |
+-----+------+-------+
我已经试过了,但它返回了一个错误:
$this->db->select("SUM(price) as total1, (SELECT SUM(price) where type=2) as total2");
$this->db->from('table');
$this->db->where('type', '1');
$query = $this->db->get();
$result = $query->result();
我还尝试了其他几种编写查询的方法,但都无济于事,而且我在 SO 中发现的所有其他方法都太复杂,对于我的简单查询来说太多了。我认为这应该是一个非常简单的查询。
最佳答案
$sql=select price from table where type=1";
$exesql=mysqli_query($sql) or die(mysqli_error());
while($row=mysql_fetch_array($exesql)){
$tpeOneprice=$tpeOneprice+$row['price'];
}
echo $tpeOneprice;
对类型 2 也这样做。
关于php - 如何在 1 个 SQL 查询中的 2 个条件下获得 2 个总和?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43647880/