Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display positive result with a plus sign (+) in 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 (-) ?

like image 528
Sporki Avatar asked May 29 '12 08:05

Sporki


People also ask

Can you use a plus sign in SQL?

The '+' operator is used for string concatenation.

What does plus do in SQL?

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.

How do you make a positive number in SQL?

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.


2 Answers

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)
like image 83
ashleedawg Avatar answered Sep 23 '22 19:09

ashleedawg


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
like image 24
juergen d Avatar answered Sep 21 '22 19:09

juergen d