SQL 转轴还是其他?

SQL Pivot or something else?

我有一个预先存在的 table(所以我无法更改此 table),如下所示:

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

我想像这样创建一个临时 table,只为一家公司选择:

查询 XXX 时,table 应如下所示:

GLSeg       Value
1           00003
2           NULL
3           00001

当查询 YYY 时,table 应该如下所示:

GLSeg       Value
1           00002
2           00004
3           NULL

我查看了 pivot 函数,但没有找到根据需要创建临时 table 的方法。

使用 cross apply(values ..) 逆透视您的数据:

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

rextester 演示: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  |
+---------+-------+-------+

仅一家公司:

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 |
+-------+-------+

将 UNPIVOT 与 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' 

输出:

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