2016-03-29 9 views
1

Ich habe zwei Spalten in meiner billing Tabelle hinzuzufügen:kann nicht DOUBLE und VARCHAR-Spalten mit CAST()

  • cost_per_month, VARCHAR
  • additional_cost, DOUBLE

Als ich:

SELECT CONCAT_WS("", "$", FORMAT(db.billing.cost_per_month, 2)) AS "Monthly Cost", 
    CONCAT_WS("", "$", FORMAT(db.billing.additional_cost, 2)) AS "Additional Cost", 
    CONCAT_WS("", "$", FORMAT(CAST(db.billing.cost_per_month AS DECIMAL(60, 2)) + db.billing.additional_cost, 2)) AS "Total Cost" 
    FROM db.billing; 

Ich bekomme:

Monthly Cost Additional Cost Total Cost 
$1,000.00  $    $ 
$0.00   $400.00   $400.00 
$250.00  $250.00   $ 

Statt:

Monthly Cost Additional Cost Total Cost 
$1,000.00  $0.00   $1,000.00 
$0.00   $400.00   $400.00 
$250.00  $250.00   $500.00 

Ich habe versucht:

  • CAST(db.billing.cost_per_month AS SIGNED) mit
  • mit CAST(db.billing.cost_per_month AS UNSIGNED)
  • die FORMAT() und CONCAT_WS() Funktionen Entfernen
  • SUM() eine Reihe von verschiedenen Möglichkeiten, verwendet

Antwort

2

das Problem auf die NULL Werte zurückzuführen ist, dass es existiert, wenn kein cost_per_month oder additional_cost für eine Zeile ist.

Eine Arbeit ist COALESCE() statt CAST() zu verwenden.

In Ihrem Fall:

SELECT CONCAT_WS("", "$", FORMAT(COALESCE(db.billing.cost_per_month, 0.00), 2)) AS "Monthly Cost", 
    CONCAT_WS("", "$", FORMAT(COALESCE(db.billing.additional_cost, 0.00), 2)) AS "Additional Cost", 
    CONCAT_WS("", "$", FORMAT(COALESCE(db.billing.cost_per_month, 0.00) AS DECIMAL(60, 2)) + COALESCE(db.billing.additional_cost, 0.00), 2)) AS "Total Cost" 
    FROM db.billing; 
+0

ignorieren meine letzte Bemerkung, Sie waren zu 100% richtig. Ich darf nicht alles richtig eingegeben haben. Entschuldigen Sie. – EVAL