0

在 SQL Server 中,我想知道如何从一行开始,例如:

create table t1
(
n1 int,
n2 int,
n3 int,
a1 char, 
a2 char,
a3 char,
b1 char, 
b2 char, 
b3 char
)

insert into t1 values (1, 2, 3, 'a', 'b', 'c', 'x', 'y', 'z')

对于将返回的查询:

n1 n2 n3 As Bs

1, 2, 3, a, x 
1, 2, 3, b, y
1, 2, 3, c, z

我要旋转的列组是静态的并且列数相等。

4

2 回答 2

2

尝试这个

SELECT n1,n2,n3,a,b
FROM 
   (SELECT * FROM t1) p
    UNPIVOT (a FOR ACOL IN (a1,a2,a3))AS u1
    UNPIVOT (b FOR BCOL IN (b1,b2,b3))AS u2
WHERE RIGHT(ACOL,1) =  RIGHT(BCOL,1);

SQL 演示

于 2013-04-18T21:39:50.190 回答
0

联合查询怎么样:

SELECT
    n1
    , n2
    , n3
    , a1 AS [As]
    , b1 AS [Bs]
FROM 
    t1
UNION ALL
SELECT
    n1
    , n2
    , n3
    , a2
    , b2
FROM 
    t1
UNION ALL
SELECT
    n1
    , n2
    , n3
    , a3
    , b3
FROM t1
order by a1
于 2013-04-18T21:31:38.423 回答