I need some t-sql help to create the column 'Grp' in the below table. Basicaly i need to create a column that states when a value exists, if it's null then exclude it from the 'Grp' column. The table is an example of my end result required (only Col1,Col2,Col3 exists now)
2 Answers
Use a few CASE expressions with a STUFF to remove leading -.
SELECT
STUFF(
(
CASE WHEN T.Col1 IS NOT NULL THEN '-Col1' ELSE '' END +
CASE WHEN T.Col2 IS NOT NULL THEN '-Col2' ELSE '' END +
CASE WHEN T.Col3 IS NOT NULL THEN '-Col3' ELSE '' END
),
1, 1, ''),
T.Col1,
T.Col2,
T.Col3
FROM
YourTable AS T
1 Comment
jarlh
Case expressions.
You can use a case when statement:
select
left(t.Grp,len(Grp)-1) as Grp,
t.col1,t.col2,t.col3
from (
select col1, col2, col3,
case when col1 is null then '' else 'col1-' +
case when col2 is null then '' else 'col2-' +
case when col3 is null then '' else 'col3-'
as Grp
from your_table
) t
