Question

Trying to use sum to show decimals, but its converting it to integer. Very unsure what is wrong. Here is the sql fiddle:

http://sqlfiddle.com/#!2/b2961/1

SQL query:

Select sum(PH) as PH from googlechart;
Was it helpful?

Solution

As per the comment of the user, they didn't intend to Sum the values of the field, but rather just wanted to use the values numerically. The answer previous was

select SUM(CAST(REPLACE(PH, ",", ".") AS DECIMAL(5,2))) from googlechart;

The actual answer should have been:

select CAST(REPLACE(PH, ",", ".") AS DECIMAL(5,2)) from googlechart;

The above should work, but the fiddle is down at the moment to test it. Saying that, really, you shouldn't store something that you want to Sum later on as a String of any type. It should instead be stored as a Decimal or equivalent in your case, and from there you should simply convert the . into a , when you are outputting the data to the user. It will both boost the speed of your queries, as well as allow you the use of the internal functions to the database, instead of having to make 3 separate calls to do the same thing.

Saying that, you have date and time separated into two separate fields as well. In most cases, you are better of storing them as a single field, and doing logic on them accordingly, as time as a value itself is often if little us unless you also know the day, and you can still do logic on just the time function if you needed to.

OTHER TIPS

Change PH value as 08.11 and 09.34 instead of 08,11 and 09,34

INSERT INTO `googlechart` (`id`, `Date`, `Time`, `PH`, `Chlorine`, `Temperature`) VALUES
(7, '2014-04-01', '09:00:00', '08,11', '9.00', '12.00'),
(9, '2014-04-02', '11:00:00', '09,34', '10.34', '2.34');

to

INSERT INTO `googlechart` (`id`, `Date`, `Time`, `PH`, `Chlorine`, `Temperature`) VALUES
    (7, '2014-04-01', '09:00:00', '08.11', '9.00', '12.00'),
    (9, '2014-04-02', '11:00:00', '09.34', '10.34', '2.34');

You have PH set to the varchar type, you could cast it to decimal.

The problem is that you used commas to separate decimals, you should use "." . And also try to avoid handling numeric types as strings. You should simply have like :

Insert into Customers(Name, Age) Values ('Bill', 4).
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top