-1

i would like to ask for help please in sql, I have a table in this form

ID    | Indicator1 | Indicator2 | Indicator3 | Indicator4
1     | 1          | 0          | 0          | 0
2     | 0          | 1          | 1          | 0
3     | 1          | 1          | 0          | 0
4     | 0          | 0          | 0          | 0

And I would like to make it look like this

ID    | Indicators
1     | Indicator1
2     | Indicator2
2     | Indicator3
3     | Indicator1
3     | Indicator2
4     | NULL

Any suggestions please ? Thank you

Kobi
  • 2,494
  • 15
  • 30
  • 2
    What DB are you using? It makes a difference on pivot questions. Technically you are asking for an 'unpivot' here. – Twelfth Mar 28 '18 at 18:07
  • 2
    Should point out that pivot/unpivot is the number one sql question asked on here and there is a silly number of previous questions that will answer this for you. – Twelfth Mar 28 '18 at 18:09
  • 1
    Possible duplicate of [Convert Rows to columns using 'Pivot' in SQL Server](https://stackoverflow.com/questions/15931607/convert-rows-to-columns-using-pivot-in-sql-server) – divibisan Mar 28 '18 at 18:25
  • i'm using sql server – Omayma GHITOU Mar 28 '18 at 18:26

3 Answers3

0

Use UNPIVOT.

SELECT p.Id,
   p.Indicators,
   p.IndicatorsValue 
FROM TableName
UNPIVOT
(
    IndicatorsValue FOR Indicators IN (Indicator1,Indicator2,Indicator3,Indicator4) 
)AS p
mvisser
  • 652
  • 5
  • 11
0
select   b.* from #temp a left join (
SELECT p.Id,
   p.Indicators
FROM #temp
UNPIVOT
(
    IndicatorsValue FOR Indicators IN (Indicator1,Indicator2,Indicator3,Indicator4) 
)AS p
where p.IndicatorsValue <>0)b on a.id=b.id
Daniel Marcus
  • 2,686
  • 1
  • 7
  • 13
0

Use UNPIVOT and add filter to remove unnecessary columns:

SELECT  DISTINCT ID, Indicators
FROM #Indicator
UNPIVOT (IndicatorsValue
FOR Indicators IN (Indicator1,Indicator2,Indicator3,Indicator4)) AS up
WHERE up.IndicatorsValue <> 0
Aura
  • 1,283
  • 2
  • 16
  • 30