I want to fetch the total bill amount of particular day, but in my database all the amount are inserted with "£" symbol. Now I want to sum all the column values.can anyone help me to find out
For example:
I have created a table called order and the columns are id, totamt. In totamt column data is inserted like float values eg. £2.00, £90.00 etc...
I have tried to add the values using Sum function in sql query. It adds the value but the total amount is wrong.
I guess, as others in comments have guessed, your totamt column has a VARCHAR() data type, not the FLOAT data type you mentioned in your question.
To solve this problem the best way, you should rework your database so your totamt column has a DECIMAL(12,2) data type. Why? Strings are hard to use for arithmetic operations as you have discovered. Also, floating-point arithmetic has some quirks making it not so good for money values.
In the meantime, you need to add code to your query to edit your totamt strings so they look like numbers before you give them to the SUM() operation.
This may work for you to convert your values. It removes the currency symbols and expresses the amount as a decimal value.
CONVERT(REPLACE(totamt,'£', ''), DECIMAL(12,2)) totamt
So you can then do
SELECT SUM(CONVERT(REPLACE(totamt,'£', ''), DECIMAL(12,2))) grand_total,
id
FROM table
GROUP BY id
Related
I need to save numbers to database as it is please see the example.
currently i save number as 22.5 and in database it is saved as 22.
number in database is set as integer
//sometimes $number can be "33.5" or "33" or "1" or "1.003"or "03"
$sql = "INSERT INTO active (name, number) VALUES ('somename','$number')";
If you make your number column as DECIMAL data type, it will hold the decimal point with all numbers. Integer columns cannot hold decimal points.
If it is not your requirement, better use VARCHAR as data type (But NOT RECOMENDED).
Hope this helps.
First of all, you need to check the structure of active table. From your question, I understand that various types of number values is going to be saved to number column. And I guess the type of number column in active table is numeric for int types. For example, INT or BIGINT or any other integer types.
Here is what I'm usually doing. Just use varchar for number field. It might not sound like professional. But it's very easy to use. By doing so, you won't have any problem with saving numeric value to the column. I have got an similar issue before while saving latitude and longitude value to the table. And php has got many functions to get actual float or int value from string. So this is an easy and simple way to fix.
One of the easiest and reliable way to save the numbers/integers/floats to the database is to convert them to string and then storing them into the database.
Note : Your database column type should be of type string/text.
One of the advantage of this method is that you can overcome the limits of int/float/double.
$string_number = (string)$number;
$float_number = (float)$string_number;
If you want to save number as 22.5 and in database. Then you need to change table column structure. Instead of Integer/Int set to float Then Next set length 10,2
for information please check below screen short
Then you get proper output Happy Programming
It's highly likely this has been answered elsewhere, I can't find anything so if you can link to another post that would be ace.
I have a MySQL table which lists tickets and payments, amongst other columns. I didn't design table and I can't change too much; adding a column is out of the question. Here's a simplified version of the table:
CREATE TABLE cases (
id INT PRIMARY,
created TIMESTAMP, -- when created in db- each day the table is truncated and a new csv imported
opened DATE, -- will differ from the timestamp, this is the column I want to group by
total DECIMAL, -- not relevant in this question but i'm totaling this by month too
tickets VARCHAR(256) -- the one I want to count, two tickets would look like '"foo1234","baa5678"', there is no pattern (i.e. Same prefix) in the tickets either
);
The tickets column references possibly multiple tickets. Each is wrapped in double quotes in the DB (I have a feeling this is a bit insecure, not my decision and I can't really change it), with each reference separated by a comma (if there is more than one).
There are other columns like client name and date closed, but they are irrelevant in this case
I've written a query which will group the rows by month, year and total the payments for each month.
I want the results to also include the count of tickets, itemized monthly. It can be assumed that there will always be at least one ticket. On the front end I either count the commas and add one, or explode by comma and count the array which works fine for a hand full of rows (there are rarely more than 4 tickets in one row), but as this will form a report of the entire database I want it to be a bit more efficient.
I don't have any code to post (I'm not looking for someone to write it for me, just point me in the right direction, maybe there is a method i'm forgetting?), as I'm not really sure where to start with it, all other posts similar to this are about grouping and totaling numbers (which I also need to do but i'm ok with that part), but nothing on how to do it with a string. SUM(), but with a string.
This is easily solved by using CONCAT_WS, read more about it here
CONCAT_WS will concatenate the strings with a seperator chosen by you, in your case you would do that with a comma: CONCAT_WS(',',string_column)
This wil give you a all the strings separated by commas. if you really need the count than you can continue with this: How to count items in comma separated list MySQL
Using this would give:
LENGTH(CONCAT_WS(',',string_column)) - LENGTH(REPLACE(CONCAT_WS(',',string_column), ',', ''))+1
+1 because you need have one more result than you have comma's
I'm trying to find the max value contained in two separate fields of my table.
The code I'm using in my model is:
$query = $this->db->query("select max($field1) as max_id_1 from default_table1");
$row1 = $query->row_array();
$query = $this->db->query("select max($field2) as max_id_2 from default_table1");
$row2 = $query->row_array();
return max($row1['max_id_1'], $row2['max_id_2']);
I'm a complete novice where PHP and CodeIgniter is concerned - as I'm sure my code demonstrates :)
It is working insofar as it's returning values, but not the maximum values I have in the fields. For instance I know there is a 4000 value but the highest returned is 750.
I'm wondering if this is because the fields are of type VARCHAR because although they predominantly contain numbers there are some that contain characters (- or &) or the word 'to' so I couldn't use the INT type.
Because of using VARCHAR is it failing to see that 4000 is larger than 750?
If so is there a way to cast the field contents as integer before checking for the max value, and will this be affected by the non-integer values in the fields?
All offers of help and advice is gratefully received.
Tony.
This can be done using SQL using MySQL's implicit type conversion:
select max(case when (field1+0)>(field2+0) then field1+0 else field2+0 end)
from default_table1
Using +0 would convert varchar to number and also ignore any characters that follow after the number. If you still need the original content, you can write the query like this:
select case when (field1+0)>(field2+0) then field1 else field2 end
from default_table1
order by case when (field1+0)>(field2+0) then field1+0 else field2+0 end desc
limit 1
Oh, oops, I've forgot the mysql part
You should do the same thing, cast to integer:
select max(cast($field1 to unsigned)) as max_id_1 from default_table1
It depends of your data, but you may try something like that
return max((int)$row1['max_id_1'], (int)$row2['max_id_2']);
Have a look to the PHP doc on string to int conversion
What you are really asking for is a way for codeigniter to convert the strings to numbers, and the find the max values of those. I don't know of any way to do this in codeigniter.
If you really want this, you have two options:
loop through all the rows in the table, and use php to parse out the number, while looking for the maximum number
Add a number column to the db, and do the string-to-number parsing in this new column whenever the values are inserted.
The first option is incredibly inefficient, and the second is probably your best bet.
I have a field in my database named "price" and it setup as varchar. It contains dollar sign as well as commas.
The values in my database are like this:
$100,000
$625,005
$115,990
$2,450,000
$137,005
and I would like it to order it like this:
$100,000
$115,990
$137,005
$625,005
$2,450,000
I tried ORDER BY 0+price and ORDER BY ABS(price) but they just outputted in the order it was in the database. Is there anyway to order this while keeping the field varchar
If at all possible, change your database to hold those values in a int, float or decimal field, depending on how much precision you need. Add the $ and all other formatting when outputting the values.
Everything else is just duct-taping around a bad database structure. It's not impossible, but it should be the very last resort when there is absolutely no way to change the database.
Fully agreeing with the above posts regarding the database design, there is a bad way anyways:
SELECT REPLACE(REPLACE(price,',',''),'$','') as cleanPrice FROM Table ORDER BY cleanPrice
The query has to do the replacements on every single row and therefore might become very slow..
Honestly you should really store these as int's and format them in PHP when you bring them out of the database, that way it's easier to work with the data and you can manipulate them as INT's.
When you pull them out you can use numeric_format to auto-add the comma's and then just add a $ infront of the price.
If you are storing multiple types of price's you can store a Currency Type in the DB too; which in this case would be USD.
I did this in Oracle quickly, so it might not work in MySQL...if not, I'm sorry. I'm only selecting the prices
select price
from table
order by (cast(substr(replace( replace('price', ',', ''), '"', '' ), 2, length(replace( replace('price', ',', ''), '"', '' ))-1) as int)
If you don't have any way of changing the DB structure you can add a computed column to the table for sorting purposes.
Unfortunately, mysql does not support computed columns, so after you create the new column you would need to add triggers (on UPDATEs and INSERTs) to compute the value for every inserted/changed row on the table.
In your trigger you would use REPLACE(REPLACE(price,'$',''),',','') for the value of the new column.
You could also create a view that has this logic in it and select from that.
The mysql documenation for creating triggers is located here
The mysql documenation for using views is located here
I have some PHP code which allows me to sort a column into ascending and descending order (upon click of a table row title), which is good. It works perfectly for my D.O.B colum (with date/time field type), but not for a quantity column.
For example, I have quantites of 10, 50, 100, 30 and another 100.
The order seems to be only appreciating the 1st integer, so my sorting of the column ends up in this order: 10, 100, 100, 30, 50... and 50, 30, 100, 100, 10.
This is obviously incorrect as 100 is bigger than 50, therefore both 100 values should appear at the end surely? It seems to me that 100 is only being taken into account as having the '1' value, then it appears before 10 because the system recognises it has another 0.
Is this normal to happen? Is there any way I can solve this problem? Thanks for any help. P.S. I can show code if necessary, but would like to know if this is a common issue by default.
Sounds like you're sorting by considering those values as strings, instead of as numbers. What's doing the sorting? PHP, or MySQL? Hard to say what's wrong without seeing the code that's actually sorting it.
Your field is probably defined as char/varchar/text/..., i.e. as string type and not a numeric type. In that case lexicographical sorting performed.
The sort is treating your data as strings instead of integers. Check the datatype of your column in the database. If that is a number and not a string, then the data is being converted to strings somewhere between the database and the sort routine.
looks like you are sorting strings and not numbers, what is the data type of the column? The only way to sort string numbers properly is to add leading zeros, but it is best to store that data in the proper type, so you don't have to do these sort of manipulations each time you select the data.
In the event that you need to leave the column as a character type for some reason, you can cast to a suitable numeric type for the ordering. This is less efficient than just changing the column though.
ORDER BY CAST(theColumn AS DECIMAL(5, 2))
http://dev.mysql.com/doc/refman/5.0/en/numeric-types.html
Your column is a text type. You can change the column type permanently, or cast it when you do the sort.
Table alter (you may want a different default value)
ALTER TABLE [Table]
MODIFY COLUMN [Column] INTEGER UNSIGNED NOT NULL DEFAULT '0';
Or cast when you sort
SELECT *
FROM [Table]
ORDER BY CAST([Column] as UNSIGNED INTEGER) ASC;