将几列连接到一个表中

时间:2016-11-01 17:13:41

标签: sql sql-server

如何将其加入一个表?

select xxx.* from
(
(select a from x where a in (q)) as kk,
(select a from x where a in (w)) as hh,
(select a from x where a in (e)) as gg
) xxx

我想得到:

gg|hh|kk
---------
1 |2 |3

(结果只是一个例子)

3 个答案:

答案 0 :(得分:1)

您要做的事情称为支点。以下是您的数据的简单示例:

WITH cte AS (
    SELECT xxx.* from
    (
    (select 1 as val, 'a' AS id) UNION ALL
    (select 2 as val, 'b' AS id) UNION ALL
    (select 3 as val, 'c' AS id)
    ) AS xxx
)
SELECT *
FROM cte AS p
PIVOT (MAX(val) FOR id IN ([a], [b], [c])) AS pvt

答案 1 :(得分:0)

好的,你没有提到的是你发布的查询不起作用(你有额外的括号)。以下是我认为你想要的答案:

从你的第一个例子......

select * 
from
(select 1 as a) as table1,
(select 2 as b) as table2,
(select 3 as c) as table3;

如果您有多列:

select table1.aa as a, table2.bb as b, table3.cc as c
from
(select 1 as aa, 11 as aaa) as table1,
(select 2 as bb, 22 as bbb) as table2,
(select 3 as cc, 33 as ccc) as table3;

两者都给:

a   b   c
1   2   3

答案 2 :(得分:-1)

这个怎么样?

select xxx.*
from (select 1 as a, 2 as b, 3 as c) as xxx;
相关问题