有没有办法将2表合并为1行

时间:2017-05-23 16:08:42

标签: sql-server sql-server-2014

我正在尝试将2个表合并为1列。无论如何我能做到吗?

例如,我有表1和表2看起来像

表1:

docker export

表2:

unit    Item
1   apple
2   ball
3   cat
4   dog
5   elephant

如果我使用:

unit    Field1
1   test1
1   test2
2   apple1
2   test1
3   ball1
3   cat1
4   dot1
4   elp
5   rat
5   rat1
5   rat2

由于表2中有多个单元,我将获得多行。

我想要的是

Select * from table1 as  a  left join table2 as b on a.unit = b.unit, 

无论如何我能得到结果吗?

谢谢

2 个答案:

答案 0 :(得分:1)

您可以使用row_number在每个单元中生成序列号,然后使用条件聚合来旋转数据

select unit,
    item,
    max(case when seqnum = 1 then field end) as field1,
    max(case when seqnum = 2 then field end) as field2,
    . . .
    max(case when seqnum = 9 then field end) as field9
from (
    select t1.unit,
        t1.item,
        t2.field,
        row_number() over (
            partition by t1.unit order by t2.field
            ) as seqnum
    from table1 t1
    join table2 t2 on t1.unit = t2.unit
    ) t
group by unit,
    item;

答案 1 :(得分:0)

尝试使用GROUP_CONCAT(Feild1)

Select a.unit , a.item , GROUP_CONCAT(Feild1) as feild1 from table1 as a left join table2 as b on a.unit = b.unit group by a.unit , a.item

结果:

Unit    Item      Feild1
1         apple     Test1,test2
........... ....
相关问题