Specify scale in a ABS function? - sql

Is it possible to specify scale in a ABS function from a decimal ?
= ABS(([Accounting].salary+ABS([Accounting].expenses))/2)
As of right now everything works correctly but there is a problem with results when the number has only 1 number after the decimal point:
100.12 - All ok
230.1 - Not ok, it should be 230.10
I want the outcome to always have two numbers after the decimal point.
The query has to work on both MS SQL Server and Oracle. I can specify the query for each db manually.

To me, this is more a user interface issue than a SQL issue.
230.1 - Not ok, it should be 230.10
Seriously, that's both the same number.
In Oracle you can convert a number into a string in order to present it to an end user.
select to_char(234.1,'$9,999.99') from dual
$234.10
Have a look at format models in the Oracle documentation.
http://docs.oracle.com/cd/B19306_01/server.102/b14200/sql_elements004.htm

Just change code:
= ABS(([Accounting].salary+ABS([Accounting].expenses))/2)
By the following:
= CAST(ABS(([Accounting].salary+ABS([Accounting].expenses))/2) AS DECIMAL(18 /*set your format here instead of 18*/,2))
I've just checked it in code:
SELECT CAST(230.1 AS DECIMAL(18 /*set your format here instead of 18*/, 2))
And all works fine
In fact, it's just a question of representation of your numbers in the UI for the user. You can convert your number to the string with using to_char () with the format specified. But it is better to define the output format on the front-end

Related

SSRS - Number format expression not working

I have a table in my database called systemconfig which has some configs that I'll use on my reports. The idea is, instead of adjusting the 'number formats' directly in the textboxes properties of the report, I just change a value in this table, and then through a custom expression in the format property, it gets the value from this table
The query of the dataset 'ds_DecimalValues' is like this:
DECLARE #DecimalValue Nvarchar(500)
SELECT #DecimalValue =
( SELECT Value as 'DecimalValue' FROM SystemConfig WHERE Key = Decimal_Value )
SELECT
DecimalValue = #DecimalValue
ok, the result of this query is ##
In the textbox properties I have this expression in the Format line:
=First(Fields!DecimalValue.Value, "ds_DecimalValue")
But the report is showing 2 decimal values instead of none. I'm not sure if the decimal values are correct on the systemconfig table, I assume that '##' is correct to show no decimal values but I'm not sure about it. Any ideas guys??
Regards.
Would something like this work for you? Should round it to the nearest integer
=Floor(First(Fields!DecimalValue.Value, "ds_DecimalValue"))
When I have done this in the past I would typically use someting like f0 or n0 as the format code.
Try using this instead of ##.
If this does not work then a couple of things to debug.
Add a textbox that contains the same expression as you are using in your format property expression, make sure it is returning what you expect
Type the format code directly in and make sure that it formats as you expected.
remember that you don't need to use quotes when using codes like f0 etc.

SQLite Time Format Issues on Data Imported from a csv. A Number of Trailing Zeros

I was trying to query the duration of a WWE wrestler in the matches which he won and here I have successfully retrieved the data:
I would like to remove those zeros and I tried the following piece of code:
strftime(%H:%M:%S, R1.time_in_match)
which doesn't work and give the following error:
': near "%": syntax error
The data I imported were from a data frame which stores the time as time object and put them into the database as type DATETIME. The typeof function used on the "time_in_match" field returned type TEXT.
I was wondering if there is any way to format the time.
Thanks!
SQLite provides 2 functions for this case:
strftime('%H:%M:%S', R1.time_in_match)
and simpler:
time(R1.time_in_match)
because:
The time() function returns the time as HH:MM:SS
(from Date And Time Functions)
See the demo.
Your expression works as intended if you surround the format specifier with single quotes:
strftime('%H:%M:%S', time_in_match)
You could also just use string functions here:
substr(time_in_match, 1, 8)
Demo on DB Fiddle

Convert String to array and validate size on Vertica

I need to execute a SQL query, which converts a String column to a Array and then validate the size of that array
I was able to do it easily with postgresql:
e.g.
select
cardinality(string_to_array('a$b','$')),
cardinality(string_to_array('a$b$','$')),
cardinality(string_to_array('a$b$$$$$','$')),
But for some reason trying to convert String on vertica to array is not that simple, Saw this links:
https://www.vertica.com/blog/vertica-quick-tip-dynamically-split-string/
https://forum.vertica.com/discussion/239031/how-to-create-an-array-in-vertica
And much more that non of them helped.
I also tried using:
select REGEXP_COUNT('a$b$$$$$','$')
But i get an incorrect value - 1.
How can i Convert String to array on Vertica and gets his Length ?
$ has a special meaning in a regular expression. It represents the end of the string.
Try escaping it:
select REGEXP_COUNT('a$b$$$$$', '[$]')
You could create a UDx scalar function (UDSF) in Java, C++, R or Python. The input would be a string and the output would be an integer. https://www.vertica.com/docs/9.2.x/HTML/Content/Authoring/ExtendingVertica/UDx/ScalarFunctions/ScalarFunctions.htm
This will allow you to use language specific array logic on the strings passed in. For example in python, you could include this logic:
input_list = input.split("$")
filtered_input_list = list(filter(None, input_list))
list_count = len(filtered_input_list)
These examples are a good starting point for writing UDx's for Vertica. https://github.com/vertica/UDx-Examples
I wasn't able to convert to an array - but Im able to get the length of the values
What i do is convert to Rows an use count - its not best performance wise
But with this way Im able to do also manipulation like filtering of each value between delimiter - and i dont need to use [] for characters like $
select (select count(1)
from (select StringTokenizerDelim('a$b$c','$') over ()) t)
Return 3

how to convert this String to Decimal

i have this String '5666,232343' and i want to convert it to Decimal, i use cast('5666,232343' as decimal(7,5)) but it returns NULL value.
Do you know why it doesn't work with CAST
Zorkolot is right. The current precision and scale that you've used is not sufficient for the value you've provided.
If you're using SQL Server 2012 or higher and you want to keep the comma in the value, then you can use the TRY_PARSE function and set a culture. It will return NULL if it encounters an error instead of not completing the statement and returning red text. This also allows you to add basic error handling to the statement, if you wanted, by getting failed conversions to return the value of zero. For example:
This is your original query (which is currently erroring) with my error handling fix:
select coalesce(try_parse('5666,232343' as decimal(7,5) using 'en-GB'),'0') as [DecimalValue]
This is the same thing as above but I've amended the decimal precision and scale so that the value is successfully converted:
select coalesce(try_parse('5666,232343' as decimal(16,6) using 'en-GB'),'0') as [DecimalValue]
This should prevent you having to perform a REPLACE either manually or by using the SQL function.
You need to cast to a decimal that can hold the value of 5666.232343.
DECIMAL(7,5) allows numbers in this format: ##.#####. The biggest number you can have then is 99.99999. You also need to take the comma out and replace it with a period:
SELECT CAST('5666.232343' as decimal(16,6)) AS [DecimalValue]
The problem is probably the comma. In some databases, some of the functions are not as internationally-sensitive as (I think) they should be. So try:
cast(replace('5666,232343', ',', '.') as decimal(7, 5))

Conversion of String to int not getting desired format

I want to convert a string to int like this:
CAST(TestSth3.Emp_Code AS int)
I need output as 1234 in crystal report, shows me correctly when i get the output from database, but in Crystal it again converts to 1,234 instead of 1234.
I am using vb.net 2008 and SQL server.
I think you need to try this solution, Replace ',' to '' in the string
Take a look on below code
CAST(REPLACE(TestSth3.Emp_Code, ',', '') AS int) As Clm
it is unclear your question i just point out some facts here
if your string is 1234
then when you try select cast(yournum,int) will give you the correct result
example
select cast('1234'as int) as num
will results
1234
or if your string is something like 1,234
then
try the following it will give results
declare #num varchar(10) ='1,234'
select CONVERT(int, replace(#num,',',''))as number
or
select CAST(replace(#num,',','') AS int)as number2
both results 1234
also you need to double check TestSth3.Emp_Code what is that ?? is it a parameter ??
if yes then need #before that and i think it is not possible to create a parameter name including .(dot) so double check that too.
UPDATE
if the problem based on crystal report then follow below steps
Right mouse click on that field, and select "Format object". Select
"Custom Style" in the Style list, and click "Customize". Untick
"Thousands Separator", and any other unwanted formatting.
Failing that, you could try selecting the field and deleting the ","
value from the property "ThousandSeperator" in your properties window.
or use below formula
CStr(YourField, 0, '')
I think this post summarises the problem much better. #MattWhitfield says:
Formatting numbers for display is something that should be done in the
display layer, and not within the database. So, in whatever
application this data ends up being used, you should format it there.
Management Studio, unfortunately, does not offer much control in this
regard.
Edit: Integers don't have formats. E.g. Six eggs are formatted as eggs, not digits, but they are still 6. The formatting has nothing to do with the number. However if you want to display the integer in a particular format (with or without thousands separator - commas), then convert it back to a string again in the report or VB form, not in the database (or leave it as a string since it's already a string).
Easy way is to use crystal report functions:
ToNumber(TestSth3.Emp_Code)