Kumar AU

Kumar AU

  • 1.3k
  • 295
  • 56.8k

In SQL how to extract multiple columns into single into single column

Apr 10 2022 2:33 AM

Hi Team,

I am trying very hard to implement the below requirements, but I am not understanding is it possible to do using sql server. Kindly suggest me.

In the below table for every ID their may be 1 X mark or 2 X marks or 3 X marks in other columns as shown in below table. So I need to write a query to get a new column name with all the X marked columns. Kindly refer the output table sample.

Name of the table - Table 1

Id CurrentAmount RiskRating ShortName NoExceptions ABCD EFGH IJKL MNOP
1010 100 2 John Krsp   X      
1011 200 5 David sku   X      
1022 300 1 Patrik   X X X  

Here is the sample data :- 

Create table table1
(
Id INt,
CurrentAmount decimal,
RiskRating int,
ShortName varchar(100),
NoExceptions varchar(10),
ABCD Varchar(10),
EFGH varchar(10),
IJKL varchar(10),
MNOP varchar(10)
)INSERT INTO table1 (Id, CurrentAmount,  RiskRating, ShortName,  NoExceptions,   ABCD,   EFGH,   IJKL,   MNOP) values (1010, 100,    2,  'John Krsp',null,'X',NULL,NULL,NULL)
INSERT INTO table1 (Id, CurrentAmount,  RiskRating, ShortName,  NoExceptions,   ABCD,   EFGH,   IJKL,   MNOP) values (1011, 200,    5,  'David sku',null,'X',null,null,null)            
INSERT INTO table1 (Id, CurrentAmount,  RiskRating, ShortName,  NoExceptions,   ABCD,   EFGH,   IJKL,   MNOP) values (1022, 300,    1,  'Patrik',null,'X','X','X',null)         
select * from table1

Expected Output :- 

Id CurrentAmount RiskRating ShortName Exception Code
1010 100 2 John Krsp ABCD
1011 200 5 David sku ABCD
1022 300 1 Patrik ABCD
1022 300 1 Patrik EFGH
1022 300 1 Patrik IJKL

Kindly let me know , is it possible to do using SQL, kindly suggest me


Answers (1)