将列转置为SQL Server行

时间:2015-08-28 16:37:36

标签: sql-server sql-server-2005 unpivot

如果我要转换为行的列都以' c'的前缀开头,如何将某些列动态转置为行。在列名称中。我有一张表如下

DECLARE @t codes 
(
  Tax CHAR(5),
  ptype CHAR(2),
  c1 CHAR(1),
  c2 char(1),
  c3 char(1)
)

insert into @t (tax, ptype, c1, c2, c3) values ('AAAAA','10',Null, 1,2)
insert into @t (tax, ptype, c1, c2, c3) values ('BBBBB','21',3, 1,NULL)
insert into @t (tax, ptype, c1, c2, c3) values ('ZZZZZ','1',NULL, NULL, 2)
insert into @t (tax, ptype, c1, c2, c3) values ('CCCCC',NULL,1,3,4)
insert into @t (tax, ptype, c1, c2, c3) values ('YYYYY','4',NULL, NULL, NULL)
insert into @t (tax, ptype, c1, c2, c3) values ('DDDDD','8',2,5,6)

如何输出ptype不在的地方' NULL'当c1,c2,c3不是' NULL' C1,C2,C3值按升序排序?

Tax   ptype  Columns value
----- -----  ------- -----
AAAAA 10     c2      1
AAAAA 10     c3      2 
BBBBB 21     c2      1
BBBBB 21     c1      3 
ZZZZZ 1      c3      2
DDDDD 8      c1      2 
DDDDD 8      c2      5
DDDDD 8      c3      6

2 个答案:

答案 0 :(得分:1)

我将使用CROSS APPLYtable valued constructor来取消数据

SELECT tax, 
       ptype, 
       columns, 
       value 
FROM   @t 
       CROSS apply (Select 'c1',c1 
                    UNION ALL 
                    Select 'c2',c2 
                    UNION ALL
                    Select 'c3',c3 ) cs(columns, value) 
WHERE  ptype IS NOT NULL 
       AND columns IS NOT NULL 
       AND value IS NOT NULL 

SQL FIDDLE DEMO

答案 1 :(得分:1)

查询

SELECT Tax 
      ,ptype
      ,[Columns]
      ,Value 
   FROM @t
     UNPIVOT (Value FOR Columns IN ( C1 , C2 , C3 ))up 

结果集

╔═══════╦═══════╦═════════╦═══════╗
║  Tax  ║ ptype ║ Columns ║ Value ║
╠═══════╬═══════╬═════════╬═══════╣
║ AAAAA ║ 10    ║ c2      ║     1 ║
║ AAAAA ║ 10    ║ c3      ║     2 ║
║ BBBBB ║ 21    ║ c1      ║     3 ║
║ BBBBB ║ 21    ║ c2      ║     1 ║
║ ZZZZZ ║ 1     ║ c3      ║     2 ║
║ CCCCC ║ NULL  ║ c1      ║     1 ║
║ CCCCC ║ NULL  ║ c2      ║     3 ║
║ CCCCC ║ NULL  ║ c3      ║     4 ║
║ DDDDD ║ 8     ║ c1      ║     2 ║
║ DDDDD ║ 8     ║ c2      ║     5 ║
║ DDDDD ║ 8     ║ c3      ║     6 ║
╚═══════╩═══════╩═════════╩═══════╝

如果要从结果集中消除空值,只需将where子句添加到上述查询

WHERE [Columname] IS NOT NULL