0

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)

enter image description here

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

1 Comment

Case expressions.
0

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

2 Comments

fix your case statement it contain multiple else
Case expression.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.