Display positive result with a plus sign (+) in SQL - sql

I have the following query:
SELECT
CONVERT(DECIMAL(11,1),SUM(Column/1000*-1)) AS NAME,
FROM
Table
The reason i have "/1000*-1" is that I would like the results to be displayed in units of thousands and inverted (negative values as positive and vice versa) with only one decimal place.
How can I get the positive values have a plus sign (+) in front of them just like the negative values have a dash sign (-) ?

You can use semicolon-separated multi-part strings with the FORMAT function (kind of like you would with custom number formats in Microsoft Excel).
A number format can have up to three sections of formatting code, separated by semicolons. These code sections define the format for positive numbers, negative numbers, and zero values, in that order:
<POSITIVE>;<NEGATIVE>;<ZERO>
example:
FORMAT(#YourValue,'+0.0;-0.0')
(Adapted from this)
I usually also hide zeros when displaying +/- signs so I use formatting string: '+0;-0;'''
SELECT FORMAT(+5,'+0;-0;''') --returns: +5
SELECT FORMAT(-5,'+0;-0;''') --returns: -5
SELECT FORMAT(-5,'+0;-0;''') --returns: <empty string>
To display zero's as well you could use formatting string: '+0;-0;0'
Applies to: tsql, azure-sql-database, sql-server-2012, sql-server-2014, sql-server-2016
More Information:
Microsoft Docs : FORMAT (Transact-SQL)
Microsoft Docs : Formatting Types
(Doc is for .net but also applies to the FORMAT function)
Microsoft Docs : SIGN (Transact-SQL)

SELECT
case
when CONVERT(DECIMAL(11,1),SUM(Column/1000*-1)) >= 0
then concat('+', CONVERT(DECIMAL(11,1),SUM(Column/1000*-1)))
else CONVERT(DECIMAL(11,1),SUM(Column/1000*-1))
end AS NAME
FROM Table

In MYSQL, this works ...
CONCAT(IF(TimeZone>0,'+',''),TimeZone)

SELECT
REPLACE(CONCAT('+', CONVERT(DECIMAL(11,1),SUM(Column/1000*-1))), '+-', '-')
FROM
Table
This approach will show +0.0, though.

Related

Format from decimal to money SQL Server 2019

I need this type of decimal number format because what I show refers to money. SP SQL Server 2019
I need to transform from this $25,000.00 a $25.000,00.
Someone could help me?
REPLACE(REPLACE(CONVERT(varchar,CAST(#MontoFinal AS money),1),'.',','),',','.') = 117.692.05
Formatting is usually best handled by the UI, but sometimes you have to do it in the database for various reasons. Sometimes you have to live with mandates, and if you have to do it in the database, it can be done.
Looking at your desired output, you want periods as separators and a comma as a decimal point, and you would also like a dollar sign. Luckily for you, this is how Argentina formats its currency, so you can just use the built-in FORMAT function. The culture string for Argentina is es-AR, so you can use that along with FORMAT:
SELECT FORMAT(123456789, 'C', 'es-AR') AS [Example];
This yields:
Example
$ 123.456.789,00
If your data is a number, you are done. If it is stored as text like in your example, you can CAST it as you were doing:
SELECT FORMAT(CAST('$25,000.00' AS MONEY), 'C', 'es-AR') AS [Example];
Which gives your desired output:
Example
$ 25.000,00
As a final note, the FORMAT function in this scenario puts a space between the dollar sign and the leading number - if you don't want the space, you can remove it:
SELECT REPLACE(FORMAT(CAST('$25,000.00' AS MONEY), 'C', 'es-AR'), ' ', '') AS [Example];
And that gives you:
Example
$25.000,00
There are other ways to get a similar result, but this is probably the easiest (I said easiest, I did not say anything about performance).
If your data is actually text and already has the correct commas and decimal points along with the dollar sign, you could use REPLACE - first replace . with something (I used _), then REPLACE the , with ., and finally REPLACE the _ with . :
SELECT REPLACE(REPLACE(REPLACE('$25,000.00', '.', '_'), ',', '.'), '_', ',') AS [Example];
And again it gives your desired output:
Example
$25.000,00
If your data is not in a consistent format to start with correct commas and decimal points, the FORMAT approach will probably work better for you.

SQL Like and Wildcard with Oracle SQL Developer

I am using SQL Developer over a backend Oracle DB. I have a record where the buyer name is Pete Hansen.
Why I try
select * from data1 where buyer = 'Pete Hansen';
I get the result, no problem. However, when I use the following, I do not get any results:
select * from data1 where buyer like 'Pete Hansen';
Also, when I try the following, I do not get any results
select * from data1 where buyer like 'Pete Hans_n';
but the following works well:
select * from data1 where buyer like 'Pete Hans_n%';
Could you please help me understand? Thanks in advance.
Your buyer column seems to be defined as char; you can see the issue reproduced in this db<>fiddle, but not when the column is varchar2.
The documentation for character comparison explains the difference between blank-padded or nonpadded comparison semantics. When you compare them with =, because both the column and the string literal are `char, blank-padded semantics are used:
With blank-padded semantics, if the two values have different lengths, then Oracle first adds blanks to the end of the shorter one so their lengths are equal. ... If two values have no differing characters, then they are considered equal. This rule means that two values are equal if they differ only in the number of trailing blanks. Oracle uses blank-padded comparison semantics only when both values in the comparison are either expressions of data type CHAR, NCHAR, text literals, or values returned by the USER function.
When the column is `varchar2 then nonpadded semantics are used:
With nonpadded semantics, ... If two values of equal length have no differing characters, then the values are considered equal. Oracle uses nonpadded comparison semantics whenever one or both values in the comparison have the data type VARCHAR2 or NVARCHAR2.
LIKE works differently. Only your final pattern with % matches, because that is allowing for the trailing spaces in the char value, while the other two patterns do not. With the varchar2 version there aren't any trailing spaces to the other two patterns also match.
It's unusual to need or want to user char columns; varchar2 is more usual. Tom Kyte opined on this many years ago.
I suspect it may have to do with trailing white spaces, which like operator is not forgiving about but = is. To test that, try
select * from data1 where trim(buyer) like 'Pete Hansen';

Regular Expression Pattern for Search in SQL

I want to search a table which has file name(s) with a {Numerical Pattern String}.PDF.
Example: 1.PDF, 12.PDF, 123.PDF 1234.PDF etc.....
select * from web_pub_subfile where file_name like '[0-9]%[^a-z].pdf'
But above SQL Query is resulting even these kind of files
1801350 Ortho.pdf
699413.processing2.pdf
15-NOE-301.pdf
Could any one help me what I am missing here.
One way to do it is getting the substring before the file extension and checking if it is numeric. This solution only works well if there is only one . character in the file name.
select * from web_pub_subfile
where isnumeric(left(file_name,charindex('.',file_name)-1)) = 1
Note:
ISNUMERIC returns 1 for some characters that are not numbers, such as plus (+), minus (-), and valid currency symbols such as the dollar sign ($).
To handle file names with mutliple . characters and if there is always a .filetype extension, use
select * from web_pub_subfile
where isnumeric(left(file_name,len(file_name)-charindex('.',reverse(file_name)))) = 1
and charindex('.',file_name) > 0
Sample demo
As suggested by #Blorgbeard in the comments, to avoid the use of isnumeric, use
select * from web_pub_subfile
where left(file_name,len(file_name)-charindex('.',reverse(file_name))) NOT LIKE '%[^0-9]%'
and len(left(file_name,len(file_name)-charindex('.',reverse(file_name)))) > 0
You can't really do what you are trying to do using plain out of the box sql. The reason you are seeing those results is that the % character matches any character, any number of times. It's not like * in a regex which matches the pervious character 0 or more times.
Your best option would probably be to create some CLR functions that implement regex functionality on the SQL Server side. You can take a look at this link to find a good place to start.
Depending on your version if 2012+, you could use Try_Convert()
select * from web_pub_subfile where Try_Convert(int,replace(file_name,'.pdf',''))>0
Declare #web_pub_subfile table (file_name varchar(100))
Insert Into #web_pub_subfile values
('1801350 Ortho.pdf'),
('699413.processing2.pdf'),
('15-NOE-301.pdf'),
('1.pdf'),
('1234.pdf')
select * from #web_pub_subfile where Try_Convert(int,replace(file_name,'.pdf',''))>0
Returns
file_name
1.pdf
1234.pdf

Format the double precision value in Postgresql

I want to get the value from postgresql with formating. The formatting is user option like they want comma separator or not and with decimal place is 2,3 or 4 like.
So now i wrote query like this.
Select to_char(rate,'FM999.00') as BasicSaleRate from table1
Its return ans 220.00. How to write the query with comma separator value like this '#,0.00'. That means the value more than thousands return with comma separator or not.
Am using postgresql 9.3
Thank you
See this reference http://www.postgresql.org/docs/9.3/static/functions-formatting.html
to_char(rate,'FM999,999.00')

SQL: insert space before numbers in string

I have a nvarchar field in my table, which contains all sorts of strings.
In case there are strings which contain a number following a non-number sign, I want to insert a space before that number.
That is - if a certain entry in that field is abc123, it should be turned into abc 123, or ab12.34 should become ab 12. 34.I want this to be done throughout the entire table.
What's the best way to achieve it?
You can try something like that:
select left(col,PATINDEX('%[0-9]%',col)-1 )+space(1)+
case
when PATINDEX('%[.]%',col)<>0
then substring(col,PATINDEX('%[0-9]%',col),len(col)+1-PATINDEX('%[.]%',col))
+space(1)+
substring(col,PATINDEX('%[.]%',col)+1,len(col)+1-PATINDEX('%[.]%',col))
else substring(col,PATINDEX('%[0-9]%',col),len(col)+1-PATINDEX('%[0-9]%',col))
end
from tab
It's not simply, but I hope it will help you.
SQL Fiddle
I used functions (link to MSDN):
LEFT, PATINDEX, SPACE, SUBSTRING, LEN
and regular expression.