1

好的,这很简单,但已经搜索了 3 个小时,仍然无法正常工作!

场景是我有一个单独成本为 2 个业务的数据库,我想将每个业务的成本相加并显示在屏幕上。现在我知道这很简单,很容易用两个 SELECTS 完成。但我想在一个查询中做到这一点!

D B

|cost|business|
|100 |   1    |
|200 |   2    |
|200 |   1    |
|300 |   2    |

所以从上表我们知道 b1 = 300 和 b2 = 500!但我的查询都不起作用!

我尝试过 UNION 和 CASE,但对它们不熟悉。我的查询:

第一次尝试:

$buscost = mysql_query("SELECT FORMAT(sum(`cost`),2) as `b1` FROM `outgoing` WHERE `business`=1 
UNION 
SELECT FORMAT(sum(`cost`),2) as `b2` FROM `outgoing` WHERE `business`=2")
or die(mysql_error());
    $buscost = mysql_fetch_array($busowe);

第二次尝试:

$buscost = mysql_query("SELECT 
CASE WHEN `business` = 1 THEN FORMAT(sum(`cost`),2) END AS `b1` ,
CASE WHEN `business` = 2 THEN FORMAT(sum(`cost`),2) END AS `b2`  
FROM `outgoing` WHERE `active`='yes' ");
$buscost = mysql_fetch_array($buscost);

*cost 设置为 float(11,2)。

我确定我很接近我只是不知道如何弄清楚,在这里找到了类似的问题,但没有一个答案有帮助!

哦,如果 i print_r,第一个只获取 b1 的总和,b2 不存在!我得到的第二个数组是第一个案例的结果集,案例2“b2”为空,但存在!我检查了表格,其中有两个业务的测试数据。

请帮助任何建议或解决方案,非常感谢。

编辑:忘记提及所有结果也需要使用 where active='yes'进行过滤

4

4 回答 4

1

您需要按以下方式分组:

SELECT business, FORMAT(sum(`cost`),2) AS cost
FROM outgoing
WHERE active = 'yes'
GROUP BY business

如果你想要格式:

business | cost
b1       | 300
b2       | 500

或者

SELECT
(
   SELECT FORMAT(sum(`cost`),2) as `b1`
   FROM `outgoing`
   WHERE `business`=1 AND active = 'yes'
   GROUP BY business
) AS b1,
(
   SELECT FORMAT(sum(`cost`),2) as `b1`
   FROM `outgoing`
   WHERE `business`=2 AND active = 'yes'
   GROUP BY business
) AS b2

如果你需要格式

b1 | b2
300| 500
于 2012-05-22T19:08:58.370 回答
0
SELECT  business, SUM(cost)
FROM    mytable
GROUP BY
        business
于 2012-05-22T19:09:00.143 回答
0

尝试

SELECT business, SUM(cost) AS totalCost FROM myTable GROUP BY business
于 2012-05-22T19:09:35.730 回答
0

你可以试试这个:

     select

 @num1:=(select sum(actor_id) from actor where actor_id%2=0)as number_1, 

@num2:=(select sum(actor_id) from actor where actor_id%2!=0)as number_2,

@num1+@num2 as TOTAL;

或者如果你需要活跃。

     select

 @num1:=(select sum(actor_id) from actor where actor_id%2=0 and  active='yes')as number_1, 

@num2:=(select sum(actor_id) from actor where actor_id%2!=0 and  active='yes')as number_2,

@num1+@num2 as TOTAL;
于 2012-05-22T19:22:37.327 回答