나는 이렇게 학습한다/Algorithm & SQL

Opposite number

daco2020 2022. 6. 11. 17:40
반응형

Very simple, given an integer or a floating-point number, find its opposite.

Examples:

1: -1
14: -14
-34: 34

You will be given a table: opposite, with a column: number. Return a table with a column: res.

 

Solution:

SELECT
  number * -1 AS res  
FROM 
  opposite

 

 

Below is a method to solve uselessly and difficultly using CASE and SIGN.

The 'SIGN' function tells whether the number is negative or positive with '1' and '-1'.

SELECT
  (CASE WHEN SIGN(number)=1 THEN number*-1
  WHEN SIGN(number)=-1 THEN number*-1 END)
  AS res
FROM 
  opposite

 

 

 

반응형

'나는 이렇게 학습한다 > Algorithm & SQL' 카테고리의 다른 글

SQL Basics: Simple GROUP BY  (0) 2022.06.13
Keep Hydrated!  (0) 2022.06.12
SQL with LOTR: Elven Wildcards  (0) 2022.06.10
SQL Basics: Raise to the Power  (0) 2022.06.09
BASICS: Length based SELECT with LIKE  (0) 2022.06.08