How to combine mulitple column adding '-' and removing '-' with value is NULL - sql

this is my Data
col1 col2 col col3 col4 col5 col6
42 A 11 18 89 16 empty
42 B 12 empty 89 14 C
36 8 9 empty empty 2 empty
this is the Script I'm running
select col1 + COALESCE ([col2]+'-','')
+COALESCE([col3]+'-','')+COALESCE([col4]+'-','')
+COALESCE([col5]+'-','')+COALESCE([col6],'') as totalCol
FROM ...
This is what I get
totalCol
42A-11-18-89-16-
42B-12- -89-14-C
368-9- - -2 -
This is what I want
totalCol
42A-11-18-89-16
42B-12-89-14-C
368-9-2

run a replace of "- " to "" after your script
also you have to remember that nulls and blank space are two different things.
Updated script
select ltrim(rtrim(replace(replace(
col1 + COALESCE ([col2]+'-','')
+COALESCE([col3]+'-','')+COALESCE([col4]+'-','')
+COALESCE([col5]+'-','')+COALESCE([col6],'') + ' ','--','-'),
'- ','')))
as totalCol
FROM ...
or assuming only blank space and not nulls
select ltrim(rtrim(replace(
[col1] + [col2]+'-' + [col3]+'-' + [col4]+'-' + [col5]+'-' + [col6] + ' '
'- ','')))
as totalCol
FROM ...

Assuming you have contrived the data to illustrate the issue (because you have col in your data, but don't use col in your query), you can easily do it this way. A dash (-) is added after all non-null data. Then, we pull all but the last character (since it will always be a dash).
I also added more code to create the data, so that you can copy/run the whole query and see that it works.
declare #tbl table (
col1 varchar(10) null,
col2 varchar(10) null,
col3 varchar(10) null,
col4 varchar(10) null,
col5 varchar(10) null,
col6 varchar(10) null,
col7 varchar(10) null
)
insert into #tbl values
('42', 'A', '11', '18', '89', '16', null),
('42', 'B', '12', null, '89', '14', 'C'),
('36', '8', '9', null, null, '2', null)
select left(x.concat_val, len(x.concat_val) - 1) as totalCol
from (
select isnull(col1 + '-', '') +
isnull(col2 + '-', '') +
isnull(col3 + '-', '') +
isnull(col4 + '-', '') +
isnull(col5 + '-', '') +
isnull(col6 + '-', '') +
isnull(col7 + '-', '') as concat_val
from #tbl
) as x
Here's the returned data:
totalCol
-----------------------------------------------------------------------------
42-A-11-18-89-16
42-B-12-89-14-C
36-8-9-2

Related

Truncate specific number of characters in SQL cells

I have Description column in a table
Description
---------------
AA Check
B1 Check
RD/AA Check
WD_FA Examine
FF Examine
AA Pass
B2 Check
Examine
The desired output
Description
---------------
Check
Examine
Pass
Basically a case statement where it truncates from the left side of the cell. NOTE that the list goes on with different names and conditions, and some cells do not need modification (like the last row), so something similar to a case statement but not returning NULL if I did not specify the condition
Thank you
This removes the data up to the 1st space
case when x like '% %'
then substring(x, charindex(' ', x) +1, 8000)
else x
end
'AA Examine Device' -> 'Examine Device'
And this extracts the last word:
case when x like '% %'
then right(x, charindex(' ', reverse(x)) -1)
else x
end
'AA Examine Device' -> 'Device'
Following the white space that you have, and using DISTINCT, this gets the last word following a white space or returns the word if it's the only word.
declare #Description table (Description varchar(64))
insert into #Description
values
('AA Check'),
('B1 Check'),
('RD/AA Check'),
('WD_FA Examine'),
('FF Examine'),
('AA Pass'),
('B2 Check'),
('Examine')
select distinct
right([Description],len([Description]) - charindex(' ',[Description]))
from #Description
You can do it like below :
select distinct substring(Description, charindex(' ', Description) + 1, len(Description))
The question is too broad, but you can use something like that
DECLARE #Product TABLE (
[Description] nvarchar(255),
Condition int
);
INSERT #Product ([Description], Condition)
select 'AA Check', 1 union all
select 'B1 Check', 2 union all
select 'RD/AA Check', 3 union all
select 'WD_FA Examine', 3 union all
select 'FF Examine', 4 union all
select 'AA Pass', 1 union all
select 'B2 Check', 5 union all
select 'Examine', 6
select
[Description],
case
when Condition = 1 then replace([Description],'AA ','')
when Condition = 2 then replace([Description],'B1 ','')
when Condition = 3 then ltrim(rtrim(right([Description],len([Description]) - 5)))
when Condition = 5 then replace([Description],'B2 ','')
when Condition = 6 then [Description]
else
''
end as 'NewDescription'
from #Product
I hope it helps 🙂
Perhaps something like this:
;WITH CTE (Column1) AS (
SELECT * FROM (
VALUES
(' AA Check '), (' B1 Check'), (' RD/AA Check '), (' WD_FA Examine '), (' FF Examine '),
(' AA Pass '), (' B2 Check '), (' Examine ')
) AS A (Column1)
)
SELECT
CASE WHEN CHARINDEX('Check', Column1) > 0 THEN SUBSTRING(Column1, CHARINDEX('Check', Column1), 5)
WHEN CHARINDEX('Examine', Column1) > 0 THEN SUBSTRING(Column1, CHARINDEX('Examine', Column1), 7)
WHEN CHARINDEX('Pass', Column1) > 0 THEN SUBSTRING(Column1, CHARINDEX('Pass', Column1), 4)
END AS Results
FROM CTE
It would be painful if you have a lot of variables though.
CREATE TABLE [A] ( [Description] VARCHAR(100));
INSERT [A]
VALUES
---------------
( 'AA Check' )
,( 'B1 Check' )
,( 'RD/AA Check' )
,( 'WD_FA Examine' )
,( 'FF Examine' )
,( 'AA Pass' )
,( 'B2 Check' )
,( 'Examine' )
,( 'Examine Device' );
SELECT DISTINCT
CASE
WHEN [Description] COLLATE Latin1_General_BIN LIKE '[A-Z][a-z]%' THEN
[Description]
WHEN [Description] COLLATE Latin1_General_BIN LIKE '[A-Z][A-Z0-9]%' THEN
SUBSTRING([Description], CHARINDEX(' ', [Description]) + 1, 8000)
END AS [Description]
FROM
[A];
DROP TABLE [A];

sql concatenate columns if one or more columns is not null

I have a table that looks something like this:
BuildingID | RouterType | RouterPort | RouterInstaller | Notes
-----------+------------+------------+-----------------+-------
282 | Linksys | 1990 | Super | NULL
307 | Sonic Wall | NULL | Greg | NULL
311 | NULL | NULL | NULL | NULL
I would like the Notes column to be the concatenation of the 2nd 3rd and 4th columns only if the column is not null.
line 1: Router Type: Linksys Router Port: 1990 Router Installer: Super
line 2: Router Type: Sonic Wall Router Installer: Greg
line 3: NULL
Also the word 'Router Type:' should only come in if the value of Router type is not null etc.
I am pretty new to SQL - any help would be greatly appreciated.
Try this:
select case when [Note] = '' then null else Note from (
select BulidingId,
case when RouterType is null then '' else 'Router Type: ' + RouterType + '; '+
case when RouterPort is null then '' else 'Router Port: ' + RouterPort + '; '+
case when RouterInstaller is null then '' else 'Router Port: ' + RouterInstaller + '; '+
case when Notes is null then '' else 'Notes: ' + Notes + '; ' [Note]
from MY_TABLE
) a
This will do it by combining Coalesce and Concat. The column names are added as labels to the column values.
select COALESCE(Notes, COALESCE(CONCAT(COALESCE(CONCAT('RouterType: ',RouterType),''),
COALESCE(CONCAT(' RouterPort: ',RouterPort ),''),
COALESCE(CONCAT(' RouterInstaller: ',RouterInstaller),'')), NULL)) as Notes
from yourTable;
Try this select query, i think it will help you:
SELECT CASE WHEN (
COL2 IS NOT NULL
AND COL3 IS NOT NULL
AND COL4 IS NOT NULL )
THEN
CONCAT(COL2,' ', COL3,' ', COL4) END as ConcatedData,
* from YOUR_TABLE;
To get the spacing correct, I recommend:
select stuff(coalesce(' RouterType: ' + RouterType), '') +
coalesce(' RouterPort: ' + RouterPort ), '') +
coalesce(' RouterInstaller: ', RouterInstaller), ''),
1, 1, ''
) as Notes
from t;
In an update:
update t
set notes = stuff(coalesce(' RouterType: ' + RouterType), '') +
coalesce(' RouterPort: ' + RouterPort ), '') +
coalesce(' RouterInstaller: ', RouterInstaller), ''),
1, 1, ''
);
Note: This will not put in a NULL value, instead using an empty string. That is easily fixed -- if it is a problem:
update t
set notes = nullif(stuff(coalesce(' RouterType: ' + RouterType), '') +
coalesce(' RouterPort: ' + RouterPort ), '') +
coalesce(' RouterInstaller: ', RouterInstaller), ''),
1, 1, ''
), ''
)
Try this update statement:
DECLARE #TEMP_TABLE TABLE (
BUILDING_ID INT,
ROUTER_TYPE VARCHAR(20) NULL,
PORT INT NULL,
ROUTER_INSTALLER VARCHAR(20) NULL,
NOTES VARCHAR(1000) NULL
)
INSERT INTO #TEMP_TABLE VALUES(1,'Linksys Router', 1990, 'Super', NULL)
INSERT INTO #TEMP_TABLE VALUES(2,NULL, NULL, NULL, NULL)
UPDATE #TEMP_TABLE
SET NOTES = COALESCE(' Router type: ' + ROUTER_TYPE,'') + COALESCE(' Port: ' + CAST(PORT AS VARCHAR),'') + COALESCE(' Router installer: ' + ROUTER_INSTALLER,'')
WHERE ROUTER_TYPE IS NOT NULL OR PORT IS NOT NULL OR ROUTER_INSTALLER IS NOT NULL
SELECT * FROM #TEMP_TABLE

sybase sql column concatenation conditionally

Please help me in concatenation the columns,
Col1 Col2 col3
a b c
a3 null null
Expected output is :
col1:a col2:b col3:c
col1:a3
expected is Do not include null column name and value both.
Thanks in advance...
Here is one method:
select stuff( coalesce('col1:' + col1, ' ') +
coalesce('col2:' + col2, ' ') +
coalesce('col3:' + col3, ' '),
1, 1, ''
) as concatted_values

what will be the result of ltrim or rtrim on whitespace string

Example:
SELECT 'A' + ltrim(' ') + 'B' --or SELECT 'A' + rtrim(' ') + 'B'
Output:
AB
So what will be the actual character after trim a whitespace string? Based on the document, the result type will either be varchar or nvarchar, so it cannot be NULL, and of course if it is NULL, it will not output AB. As there is nothing between A and B, it is not neither whitespace and NULL, what is the actual output, or what is the corresponding varchar or nvarchar for that missing character? Any ASCII reflects that?
UPDATE:
After run this:
select ASCII(rtrim(' '))
The result is NULL, but why A + NULL + B will output AB instead of AB?
Thanks :)
The ASCII function produces the null result, not the TRIM function:
SELECT ASCII('')--NULL
SELECT ASCII(rtrim(' '))--NULL
SELECT rtrim(' ')--empty string
SELECT 'A' + ltrim(' ') + 'B'--'A' + empty string + 'B' = 'AB'
The data type of the concatenation result now depends on implicit conversions on which the constraints take priority:
SELECT CAST(sql_variant_property((SELECT 'A' + ltrim(' ') + 'B'),'BaseType') as varchar(20))
SELECT CAST(sql_variant_property((SELECT N'A' + ltrim(' ') + 'B'),'BaseType') as varchar(20))
SELECT CAST(sql_variant_property((SELECT 'A' + ltrim(' ') + N'B'),'BaseType') as varchar(20))
SELECT CAST(sql_variant_property((SELECT N'A' + ltrim(' ') + N'B'),'BaseType') as varchar(20))

Combine 3 Column when one of the value is empty( not null) remove extra space

Data
col1 col2 col3
5121 w river road
5512 empty pine road
query 1
Select LTRIM(ISNULL(Col1+' ','')+ ISNULL(col2+' ', '') + ISNULL(col3+' ','') as col4 from ...
query 2
Select LTRIM(COALESCE(Col1+' ','')+ COALESCE(col2+' ', '') + COALESCE(col3+' ','') as col4 from ...
for both results i get this values
5121 w river road ( this looks good )
5512 pine road ( i get extra space for col 2 )
Thank you
The problem is you have three cases
NULL
Length = 0
Length > 0
DEMO
CREATE TABLE Table1
([col1] varchar(5), [col2] varchar(5), [col3] varchar(20))
;
INSERT INTO Table1
([col1], [col2], [col3])
VALUES
('5121', 'w', 'river road'),
('5512', null, 'pine road'),
('3333', '', 'death valley')
;
SELECT COALESCE(CASE WHEN col1 = '' THEN '' ELSE col1 + ' ' END, '') +
COALESCE(CASE WHEN col2 = '' THEN '' ELSE col2 + ' ' END, '') +
COALESCE(CASE WHEN col3 = '' THEN '' ELSE col3 + ' ' END, '')
FROM Table1
OUTPUT
Original OP and Jhon version work OK with NULL and length > 0 but fail with length = 0
Consider Concat() if 2012+
As you can see with col2 ... null+' ' will result in a null, the good news is concat() represents nulls as ''
Declare #YourTable table (col1 varchar(50),col2 varchar(50),col3 varchar(50))
Insert Into #YourTable values
('5121','w', 'river road'),
('5512','','pine road'),
('1313',null,'mocking bird lane')
Select concat(nullif(col1,'')+' ',nullif(col2,'')+' ',nullif(col3,''))
From #YourTable
Returns
5121 w river road
5512 pine road -- No Extra Space
1313 mocking bird lane -- NULLs handled