SQL - Combine two strings having the second string always right aligned - sql

I'm currently trying to attain alignment via SQL queries when combining two columns.
my current data set looks something like:
Col1 Col2
usd US Dollar
cad Canadian Dollar
mxn Mexican Peso
And I want to combine col1 + col2, but no matter how many characters are in col2, the data that comes out of col1 needs to always be aligned to the right in the display.
The display is limited at 49 characters. Col2 has no specific limit as it's a description column, while col1 is a percentage column so it will have a maximum of 7 characters: 100.00%
Any help will be appreciated.
Thanks

If I understood your question well and assuming that col1 has maximal length of 7 characters while col2 length is undetermined, the following query should give you the results needed:
SELECT
ISNULL(myTable.col1, '')
+ (CASE WHEN LEN(ISNULL(myTable.col2, '')) < 49 - LEN(ISNULL(myTable.col1, ''))
THEN SPACE(49 - LEN(ISNULL(myTable.col1, '')) - LEN(ISNULL(myTable.col2, '')))
+ ISNULL(myTable.col2, '')
ELSE ' ' + LEFT(ISNULL(myTable.col2, ''),
49 - LEN(ISNULL(myTable.col1, '')) - 1)
END) AS cols_for_49chars_display
FROM
myTable
Since col1 is assumed to have max length of 7 characters, the CASE statement verifies the length of col2 for specific row.
If it's lower than 49 - LEN(col1), prepend col2 with 49 - LEN(col1) - LEN(col2) spaces using TSQL SPACE function (docs here) to right-align col2 and then add col2 itself.
In opposite case add one space after col1 and left-cut col2 to the length of 49 - LEN(ISNULL(myTable.col1, '')) - 1 when 1 being the length of the added single space character.
Example input data and results of the query:
Lets take as an example the data provided in your answer adding an extra row to show what will happen when col2 value is too long:
myTable contents:
col1 col2
------------------------------------------------------------------------------------------------
usd US Dollar
cad PCanadian Dollar
mxn Mexican Peso
dummy Very long description of a "dummy" currency that in fact doesn't exist in the real world
The result of the query on above rows would be:
cols_for_49chars_display
-------------------------------------------------
usd US Dollar
cad PCanadian Dollar
mxn Mexican Peso
dummy Very long description of a "dummy" currency
I hope it helps at least slightly.

Related

Counting a value in one cell

I'm still new to SQL and I'm trying to figure out how to count the values within one cell.
Don't mind my Excel formula I was trying to calculate the data so I wouldn't have to go through SQL.
This is what I am coming up with, but it is counting the whole column and not the cell.
SELECT COUNT(Binlocation1) FROM BinLoc
Here's a solution in the Microsoft SQL Server dialect:
SELECT
-- Include any existing columns in the table.
*,
-- Calculate a new column: 'BinLocationQuantity'.
(DATALENGTH(BinLocation1) - DATALENGTH(REPLACE(BinLocation1, ', ', ''))) / DATALENGTH(', ') + 1
AS BinLocationQuantity
FROM BinLoc
The idea is to
Determine how much the ', ' separator contributes to the length of the text in the BinLocation1 field. We do this by taking the difference between (a) the length of the field, and (b) the length of the field when all occurrences of the separator are removed (REPLACEd with the empty '' string). Here we use DATALENGTH() rather than LEN(), to avoid confusion over whitespace.
Determine how many such separators there are. We do this by taking the total length (above) contributed by all the separators, and then dividing it by the length of a single separator: DATALENGTH(', ').
Extrapolate how many values are in the BinLocation1 text. We do this by adding 1 to the number (above) of separators:
-- 1 2 3 4 N + 1
'value1, value2, value3, value4, ..., valueN'
-- ^^ ^^ ^^ ^^
-- 1 2 3 N
Warning
The assumption must hold that each BinLocation1 text is of the form
'value1, value2, value3, value4'
and has neither any missing separators
'value1 value2, value3value4'
-- ^ ^
nor any extra separators:
', value1, value2, , value3, value4, '
-- ^^ ^^ ^^

Oracle - Divide a string based on total length of string

I have a non standardized data in one of the column and I need to be splitting the data into 3 parts.
there is no specific requirement on length each column should have. It's just that the entire data to be split into 3
Input Data 01 : test , test ,test/test
Input data 02: Test; test,test\testing123data123datadatatawerr
OutPut 01: Col1=test Col2= test,test Col3=/test
Output 02: Col1= Test; col2= test,test col3=\testing123data123datadatatawerr
Is there a way to take the total length and based on that divide into 3 parts.
Concatenating of split data I need to get the entire string back.
I need to be splitting the data into 3 parts. there is no specific requirement on length each column should have
The simplest approach is to use substr():
select
substr(col, 1, 1) col1,
substr(col, 2, 1) col2
substr(col, 3) col3
from mytable
The first two columns contain one character each, starting from the beginning of the string; the last column contains the reminder. This guarantees that each column will be fed (provided that the string is at least 3 characters).
On the other hand if you want to split in three parts whose length is close to equal, you can do:
select
substr(col, 1, round(length(col) / 3)) col1,
substr(col, 1 + round(length(col) / 3), round(length(col) / 3)) col2
substr(col, 1 + 2 * round(length(col) / 3)) col3
from mytable

Change comma to dot for every cell in column

In my table I have column with numbers. These numbers uses a comma as the decimal separator. I would like a dot instead for the comma for every cell in this column.
This is what I have:
Col1 Col2 NumCol
Value 1 Value 2 12,3
Value 3 Value 4 1,23
Value 5 Value 6 99,8
This is what I want:
Col1 Col2 NumCol
Value 1 Value 2 12.3
Value 3 Value 4 1.23
Value 5 Value 6 99.8
I am familiar with the REPLACE-function. However I don't know how to use it when it involves a whole column. How would a function like that look like?
Use replace()
select t.col1, t.col2, t.NumCol, replace(numcol, ',', '.') as NewNumCol
from table t;
EDIT : As side noted by #barthofland if you have large value then only one replace() might fail. So, you need instead :
replace(replace(numcol, '.', ''), ',', '.')

SQL Server: How to display a specific character based on position in a column

So I'm attempting to display a single character based on its position in a string from one column. Since this is grid data, there is a simple math to it. The grid has 24 rows 'A-X', and 44 columns.
So lets say I want to see the value in D9. I already know the expected value should be a 'A1', so that means the character length is '2'. If I do the math: (A + B + C = 3 x 44, + 9). That two-character value for D9 starts at the 141st position of that string in Col2. I attempted to use SUBSTRING with no success
SELECT
Col1 , SUBSTRING('Col2',141,2)
FROM Table1
Query result displays data in Col1, but for Col2 its just blank. What am I missing?
Asked too soon. Figured out I had to remove the ' from the column name
SELECT
Col1 , SUBSTRING('Col2',141,2)
FROM Table1
Didn't work
SELECT
Col1 , SUBSTRING(Col2,141,2)
FROM Table1
Works

SQL - Select only one value from multiple fields

Assume the following
col1 col2 col3 col4
------+----------+---------+---------
abc | | |
Yes, col1-4 have a space in them!
I want to select the column that is not a space . On row 1 it's col1, but on row 20 it may be col3, row 55 it may be col2, and so on. I need to return just that column.
There will always be only one column with a stored value within this range of four columns, I just need the one that actually has information in it.
This will be part of a greater query for a report, so regardless of what column abc is in I need that to look the same in every result case. Meaning I can't have the results be col1 for one case and col2 for the other because the report won't recognize. The column needs to always be called the same.
Yes, I know it's better to store NULLS versus spaces and why use four columns when only one can have data, why not use one. I've complained enougth about that so don't rip me a new one about bad db design because I AGREE.
SELECT LTRIM(RTRIM(col1 + col2 + col3 + col4))
Here we go... Why not add bad code to bad design. You could technically add all of the columns together and then trim them for leading/trailing spaces. I don't recommend it for performance on large scale deployments. Heck, I don't recommend this for any production script but I've been here before... Gotta do what you can to get it done.
Why not use a CASE statement, like
CASE WHEN col1 <> ' ' THEN col1
WHEN col2 <> ' ' THEN col2
WHEN col3 <> ' ' THEN col3
WHEN col4 <> ' ' THEN col4
END
You can do this:
case
when col1 != '' then col1
when col2 != '' then col2
...
end