将列转为行 SQL 服务器

Transpose columns to rows SQL Server

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

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

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

查询

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