简体   繁体   中英

SQL Pivot or something else?

I have a pre-existing table (so I can't change this table) like this:

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

I would like to create a temp table like this, selecting for just one company:

When querying for XXX the table should look like this:

GLSeg       Value
1           00003
2           NULL
3           00001

When querying for YYY the table should look like this:

GLSeg       Value
1           00002
2           00004
3           NULL

I have looked at the pivot function but am not seeing a way to create the temp table as needed.

using cross apply(values ..) to unpivot your data:

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

rextester demo: http://rextester.com/ZKTD58113

returns:

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

For just one company:

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

returns:

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

Using UNPIVOT with 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' 

Output:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM