如何在1个SQL查询中的2个条件中获得2个总和?

时间:2017-04-27 02:54:22

标签: php mysql codeigniter

我有一张桌子如下图所示。如何选择SUM列价格WHERE type = 1 AND type = 2?我想要一个查询中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中找到的所有其他方法对于我的简单查询来说过于复杂和过多。我认为这应该是一个非常简单的查询。

5 个答案:

答案 0 :(得分:3)

Activity

对类型2也这样做。

答案 1 :(得分:1)

试试这个:

$this->db->select("SUM(price) as total1, (SELECT SUM(price) from table where type=2) as total2");
$this->db->from('table');
$this->db->where('type', '1');
$query = $this->db->get();
$result = $query->result();

答案 2 :(得分:0)

这将为您提供两个总数:

SELECT
    SUM(IF(type=1,price,0)) AS Total1,
    SUM(IF(type=2,price,0)) AS Total2
FROM table
WHERE type in (1,2)

答案 3 :(得分:0)

我认为 group by 是您需求的最佳选择(选项2 )。

选项1:

$query = $this->db->query("select SUM(CASE WHEN type= '1' then 1 else 0 end) as total1, SUM(CASE WHEN type= '2' then 1 else 0 end) as total2 from table");
$result = $query->result();

PS:您还可以在类型列上使用分组依据。

使用分组依据(选项2):

$this->db->select("SUM(type)");
$this->db->from('table');
$this->db->group_by('type');
$query = $this->db->get();
$result = $query->result();

答案 4 :(得分:0)

我刚试过mysql。

试试这个:

SELECT type, SUM(price) FROM test GROUP BY type