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 (-) ?
The '+' operator is used for string concatenation.
SQL*Plus has its own commands and environment, and it provides access to the Oracle Database. It enables you to enter and execute SQL, PL/SQL, SQL*Plus and operating system commands to perform the following: Format, perform calculations on, store, and print from query results. Examine table and object definitions.
To compute the absolute value of a number, use the ABS() function. This function takes a number as an argument and returns its value without the minus sign if there is one. The returned value will always be non-negative – zero for argument 0, positive for any other argument.
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
FORMAT
(Transact-SQL) FORMAT
function)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With