2017-09-15 5 views
1

J'ai une table pré-existante (donc je ne peux pas changer ce tableau) comme ceci:Pivot SQL ou autre chose?

Company  GLSeg1  GLSeg2  GLSeg3 
XXX   00003  NULL  00001 
YYY   00002  00004  NULL 

Je voudrais créer une table temporaire comme celui-ci, la sélection pour une seule entreprise:

lorsque vous interrogez XXX la table devrait ressembler à ceci:

GLSeg  Value 
1   00003 
2   NULL 
3   00001 

lors de l'interrogation pour YYY la table devrait ressembler à ceci:

GLSeg  Value 
1   00002 
2   00004 
3   NULL 

J'ai regardé la fonction pivot mais je ne vois pas comment créer la table temporaire si nécessaire.

Répondre

0

utilisant cross apply(values ..) à UNPIVOT vos données:

select t.Company, v.GLSeg, v.Value 
from t 
    cross apply (values 
    (1,glseg1),(2,glseg2),(3,glseg3) 
) v (GLSeg,Value) 

rextester démonstration: http://rextester.com/ZKTD58113

retourne:

+---------+-------+-------+ 
| Company | GLSeg | Value | 
+---------+-------+-------+ 
| xxx  |  1 | 00003 | 
| xxx  |  2 | NULL | 
| xxx  |  3 | 00001 | 
| yyy  |  1 | 00002 | 
| yyy  |  2 | 00004 | 
| yyy  |  3 | NULL | 
+---------+-------+-------+ 

Pour une seule entreprise:

select v.GLSeg, v.Value 
from t 
    cross apply (values 
    (1,glseg1),(2,glseg2),(3,glseg3) 
) v (GLSeg,Value) 
where t.company = 'xxx' 

retours:

+-------+-------+ 
| GLSeg | Value | 
+-------+-------+ 
|  1 | 00003 | 
|  2 | NULL | 
|  3 | 00001 | 
+-------+-------+ 
0

Utilisation UNPIVOT avec COALESCE:

SELECT COMPANY 
     , STUFF(SUBJECT,1,5,'') AS GLSEG 
     , CASE WHEN VALUE ='<NULL>' THEN NULL ELSE VALUE END AS VALUE 
    FROM (SELECT COMPANY 
       , COALESCE(GLSEG1,'<NULL>') AS GLSEG1 
       , COALESCE(GLSEG2,'<NULL>') AS GLSEG2 
       , COALESCE(GLSEG3,'<NULL>') AS GLSEG3 
     FROM SEG_COMP) A 
    UNPIVOT(VALUE FOR SUBJECT IN (GLSEG1, GLSEG2,GLSEG3)) U 
    WHERE COMPANY='XXX' 

Sortie:

COMPANY GLSEG VALUE 
XXX  1  00003 
XXX  2  NULL 
XXX  3  00001