2012-08-06 45 views
1

好吧,我有一个mySQL的值表。有些是积极的,有些是消极的。消极的东西在桌子上有一个 - 面前。我正在使用Codeigniter。总和所有值,忽略减号

我需要将它们总结在一起,但IGNORE - 在负值之前。我只想总结这些数字,而不是将它们总和为负数。

因此,举例来说,这是它目前的作用: -55 + -20 = 35

但我希望它做的是: -55 + -20 = 75

基本上我只想总结这些值,不管它们是正面还是负面的类型。

我该怎么做?这里是我的查询:

$this->db->select_sum('vat') 
    ->from('accounts')->where_in('type', 'Expenses') 
    ->where('date <=', $current_period) 
    ->where('date >=', $previous_period); 
+5

你可以使用 “SUM(ABS())” – Shubhansh 2012-08-06 13:26:12

回答

5

也许这样的事情会工作:

$this->db->select('SUM(CASE WHEN vat >= 0 THEN vat ELSE -vat END) AS sum', false)->from('accounts')->where_in('type', 'Expenses')->where('date <=', $current_period)->where('date >=', $previous_period); 

这应该保持正数在vat正,将负数转正。注意:select()语句中的false停止自动转义字段的CI。

而且,从@shubhansh评论拾起,你可以使用MySQL的ABS()方法来获取绝对值而非CASE

$this->db->select('SUM(ABS(vat)) AS sum', false)->from('accounts')->where_in('type', 'Expenses')->where('date <=', $current_period)->where('date >=', $previous_period); 
+0

唉唉是你的第二一个使用ABS()工作太棒了。谢谢! – 2012-08-06 13:43:55

+0

@NoahGoodrich没问题!很高兴起作用=] – newfurniturey 2012-08-06 13:47:27

0

我能想到的两种方法。

第一种方式:我敢肯定,CI逃脱字段名,所以这种方式,您需要执行正常的查询做到这一点:

$this->db->query('SELECT SUM(AVG(vat)) FROM accounts WHERE ...'); // Replace ... with WHERE parameters 

方式二:还是做两个查询,总结的结果:

$positive = $this->db->select_sum('vat')->from('accounts')->where_in('type', 'Expenses')->where('date <=', $current_period)->where('date >=', $previous_period)->where('vat >=', 0); 
$negative = $this->db->select_sum('vat')->from('accounts')->where_in('type', 'Expenses')->where('date <=', $current_period)->where('date >=', $previous_period)->where('vat <', 0); 
$result = $positive + abs($negative); 

请注意,第二个选项需要更长的时间才能完成,因为这是两个单独的查询。

0

我有同样的问题做一个数据库级日期搜索 - 最好我可以做的是使用ABS(),因为如果结果是过去,time_diff返回负值。

TIME(ABS(TIMEDIFF(TIME(sch_Starts), TIME("22:00:00")))) 

需要的可能是阴性结果,通过ABS转换它,敷的时间()周围如果u使用的是像我的时间特定的功能转换回时间:如果与date_diff或TIME_DIFF使用该工作。

乏味也许,但它的工作原理100%

-1

你总是可以尝试:

where table.field NOT LIKE '%-%'