将列映射到行

时间:2019-06-12 18:53:53

标签: sql ms-access

我有一个包含以下字段的表:

AS1|BS1|AS2|BS2|AS3|BS3|
...N rows...

我想基于第一个表创建具有以下结构的新表:

Label|S1|S2|S3|
  A  |  |  |  | (This row contains the value of AS1|AS2|AS3)
  B  |  |  |  | (This row contains the value of BS1|BS2|BS3)
...(2*N rows total because there was 2 type of label)...

我知道如何在C#中执行此操作,但是仍然可以通过SQL语句直接执行此操作吗?

我已经尝试的东西:

SELECT "A" as LABEL, AS1 as S1, AS2 as S2, AS3 FROM MyTABLE

但是如何对同一SQL语句中的“ B”标签执行相同操作?

我的问题是针对MS ACCESS DB,但可以随意使用您知道的任何SQL,如果可能,我会尝试将其改编为ACCESS。

2 个答案:

答案 0 :(得分:1)

您可以使用UNION ALL来完成

select 'A' as Label
   , AS1 as S1
   , AS2 as S2
   , AS3 as S3
from Table
UNION ALL
select 'B' as Label
   , BS1 as S1
   , BS2 as S2
   , BS3 as S3
from Table

答案 1 :(得分:1)

您可以union将这两个集合放在一起,例如:

select 'A' as label, t1.as1 as s1, t1.as2 as s2, t1.as3 as s3
from mytable t1
union all
select 'B' as label, t2.bs1 as s1, t2.bs2 as s2, t2.bs3 as s3
from mytable t2