将2个表中的2列组合成一列

时间:2015-03-13 10:29:47

标签: sql sql-server sql-server-2012

我的tab1包含以下数据

ID |  Name
1  |   furniture
2  |   Electronic
3  |   Books

tab2 as

foreignkeyID |名称

1            |   sofa
1            |   chair
3            |   c#
3            |   sql
2            |   fan
2            |   tv

我希望结果集为

Name
furniture
sofa
chair
Electronic
FAN
TV
Books
c#
sql

我使用cursor实现上述结果集,while循环,如何在没有循环的情况下获得所需的输出

2 个答案:

答案 0 :(得分:4)

试试这个,

Declare @tab1 table(ID int,  Name varchar(40))
insert into @tab1 values(1 ,'furniture')
,(2,'Electronic'),(3,'Books')

declare @tab2 table(foreignkeyID int, Name varchar(40))
insert into @tab2 values
(1,'sofa'),
(1,'chair'),(3,'c#'),(3,'sql'),
(2,'fan'),(2,'tv')

select name from
(select 1 rn, id, name from @tab1
union all
select 2, foreignkeyID, name from @tab2
)t4
order by  id,rn

答案 1 :(得分:1)

一个简单的UNION可以完成这项工作。或者对于某些不同的东西,您可以使用recursive CTE。通常,当存在多个级别时,会使用递归CTE,但没有理由不能将相同的技术仅用于1个级别。

declare @t1 table (id int, category varchar(100))
insert @t1 values (1, 'furniture'), (2, 'Electronic'), (3, 'Books')

declare @t2 table (id int, item varchar(100))
insert @t2 values (1, 'sofa'), (1, 'chair'), (3, 'c#'), (3, 'sql'), (2, 'fan'), (2, 'tv')

-- Approach 1 : UNION

; with cte as (
    select
        id, 0 as level, category as name
    from
        @t1
    union all
    select
        id, 1 as level, item as name
    from
        @t2
)
select
    name
from
    cte
order by
    id, level

-- Approach 2 : Recursive CTE

; with cte as (
    select
        id, category as name, 0 as level
    from @t1
    union all
    select 
        t2.id, t2.item, level + 1 
    from
        @t2 t2 
            inner join cte on cte.id = t2.id
                         and level = 0
)
select
    name
from
    cte
order by
    id, level