2014-10-18 48 views
0

想要從替換字段的總和中獲得每個ID的總數。MySQL替換字符串SUM然後總計

SELECT 
    insurance_carrier as ID, SUM(REPLACE(REPLACE(REPLACE(es_reserve,'$',''),',',''),'-','')) AS es_reserve, 
    SUM(REPLACE(REPLACE(REPLACE(structure_reserve,'$',''),',',''),'-',''))AS structure_reserve, 
    SUM(es_reserve+structure_reserve) AS total 
FROM job_tbl 
WHERE 
    job_status NOT IN(2,4,6,7,9) AND 
    insurance_carrier !=0 AND  
    FROM_UNIXTIME(date_of_loss,'%m') = MONTH(NOW()) AND 
    FROM_UNIXTIME(date_of_loss,'%Y') = YEAR(NOW()) 
GROUP BY insurance_carrier 

我從es_reserve和structure_reserve結果,但總爲0

BTW字段包含像$ 2,300-項是用於替換

任何幫助,將不勝感激的理由! !

編輯:這裏是這將產生的結果

Array 
(
[ID] => 14 
[es_reserve] => 5000 
[structure_reserve] => 35000 
) 

Array 
(
[ID] => 15 
[es_reserve] => 2500 
[structure_reserve] => 2500 
) 

Array 
(
[ID] => 41 
[es_reserve] => 2500 
[structure_reserve] => 2500 
) 

Array 
(
[ID] => 44 
[es_reserve] => 2500 
[structure_reserve] => 
) 

這是我想它產生

Array 
(
[ID] => 14 
[es_reserve] => 5000 
[structure_reserve] => 35000 
[total] => 40000 
) 

Array 
(
[ID] => 15 
[es_reserve] => 2500 
[structure_reserve] => 2500 
[total] => 5000 
) 

Array 
(
[ID] => 41 
[es_reserve] => 2500 
[structure_reserve] => 2500 
[total] => 5000 
) 

Array 
(
[ID] => 44 
[es_reserve] => 2500 
[structure_reserve] => 
[total] => 2500 
) 

回答

1

總計列正在做原來的列值之和時,別名定義該選擇不會在同一個選擇中使用。 可以重複REPLACE語句,而這樣做總列運算

SUM( REPLACE(REPLACE(REPLACE(es_reserve,'$',''),',',''),'-','') 
     + REPLACE(REPLACE(REPLACE(structure_reserve,'$',''),',',''),'-','')) 
Total, 

,而不是

SUM(es_reserve+structure_reserve) as total 

查詢變得與爲了在評論作爲問道。

SELECT insurance_carrier as ID, SUM(REPLACE(REPLACE(REPLACE(es_reserve,'$',''),',',''),'-','')) AS es_reserve, SUM(REPLACE(REPLACE(REPLACE(structure_reserve,'$',''),',',''),'-',''))AS structure_reserve, SUM(REPLACE(REPLACE(REPLACE(es_reserve,'$',''),',',''),'-','') + REPLACE(REPLACE(REPLACE(structure_reserve,'$',''),',',''),'-','')) as Total FROM job_tbl WHERE job_status NOT IN(2,4,6,7,9) AND insurance_carrier !=0 AND FROM_UNIXTIME(date_of_loss,'%m') = MONTH(NOW()) AND FROM_UNIXTIME(date_of_loss,'%Y') = YEAR(NOW()) GROUP BY insurance_carrier 
order by SUM(REPLACE(REPLACE(REPLACE(es_reserve,'$',''),',',''),'-','') + REPLACE(REPLACE(REPLACE(structure_reserve,'$',''),',',''),'-','')) desc 

OR 使用它作爲子查詢

SELECT T.*,  SUM(es_reserve+structure_reserve) AS total 
FROM 
(

SELECT 
    insurance_carrier as ID, SUM(REPLACE(REPLACE(REPLACE(es_reserve,'$',''),',',''),'-','')) AS es_reserve, 
    SUM(REPLACE(REPLACE(REPLACE(structure_reserve,'$',''),',',''),'-',''))AS structure_reserve 

FROM job_tbl 
WHERE 
    job_status NOT IN(2,4,6,7,9) AND 
    insurance_carrier !=0 AND  
    FROM_UNIXTIME(date_of_loss,'%m') = MONTH(NOW()) AND 
    FROM_UNIXTIME(date_of_loss,'%Y') = YEAR(NOW()) 
GROUP BY insurance_carrier 
) T 
+0

我們能做些什麼,以避免重複和允許更可讀的查詢? – 2014-10-18 01:15:13

+0

@ 2unco,更新它,我們可以使用子查詢。 – radar 2014-10-18 01:18:04

+0

幹得好先生/女士! – 2014-10-18 01:23:48