SQL Pivot还是其他什么?

时间:2017-09-15 12:01:53

标签: sql sql-server sql-server-2008 pivot unpivot

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

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

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

查询XXX时,表格应如下所示:

GLSeg       Value
1           00003
2           NULL
3           00001

查询YYY时,表格应如下所示:

GLSeg       Value
1           00002
2           00004
3           NULL

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

2 个答案:

答案 0 :(得分:0)

使用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

返回:

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

返回:

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

答案 1 :(得分:0)

将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