SQL Challenges-1: Convert negative numbers to positive and vice verse
SQL Challenges-1: Exercise-11 with Solution
From the following table, write a SQL query to convert negative numbers to positive and vice verse. Return the number.
Input:
Table: tablefortest
Structure:
Field | Type | Null | Key | Default | Extra |
---|---|---|---|---|---|
srno | int(11) | YES | |||
pos_neg_val | int(11) | YES |
Data:
srno | pos_neg_val |
---|---|
1 | 56 |
2 | -74 |
3 | 15 |
4 | -51 |
5 | -9 |
6 | 32 |
Sample Solution:
SQL Code(MySQL):
DROP TABLE IF EXISTS tablefortest;
CREATE TABLE tablefortest(srno int, pos_neg_val int);
INSERT INTO tablefortest VALUES (1, 56);
INSERT INTO tablefortest VALUES (2, -74);
INSERT INTO tablefortest VALUES (3, 15);
INSERT INTO tablefortest VALUES (4, -51);
INSERT INTO tablefortest VALUES (5, -9);
INSERT INTO tablefortest VALUES (6, 32);
select * from tablefortest;
SELECT srno,pos_neg_val,-1 *(pos_neg_val) AS converted_signed_value
FROM tablefortest;
Sample Output:
srno|pos_neg_val|converted_signed_value| ----|-----------|----------------------| 1| 56| -56| 2| -74| 74| 3| 15| -15| 4| -51| 51| 5| -9| 9| 6| 32| -32|
SQL Code Editor:
Contribute your code and comments through Disqus.
Previous: Find active customers.
Next: Century of a given date.
SQL: Tips of the Day
SQL Server SELECT into existing table.
INSERT INTO dbo.TABLETWO SELECT col1, col2 FROM dbo.TABLEONE WHERE col3 LIKE @search_key
This assumes there's only two columns in dbo.TABLETWO - you need to specify the columns otherwise:
INSERT INTO dbo.TABLETWO (col1, col2) SELECT col1, col2 FROM dbo.TABLEONE WHERE col3 LIKE @search_key
Database: SQL Server
Ref: https://bit.ly/3y6tpA3
- New Content published on w3resource:
- HTML-CSS Practical: Exercises, Practice, Solution
- Java Regular Expression: Exercises, Practice, Solution
- Scala Programming Exercises, Practice, Solution
- Python Itertools exercises
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework
- Angular - JavaScript Framework
- Vue - JavaScript Framework
- Jest - JavaScript Testing Framework