SQL将多个行合并为一个具有多个列的行。

时间:2021-03-22 19:46:05

I've got multiple rows in my result from my query:

我的查询结果中有多行:

for example, the table "Address":

例如,表“地址”:

Street | Number | City
----------------------
A1     | A2     | A3
B1     | B2     | B3

What I actually want is:

我真正想要的是:

Address1_Street | Address1_Number | Address1_City | Address2_Street | Address2_Number | Address2_City
------------------------------------------------------------------------------------------------------
A1              | A2              | A3            | B1              | B2              | B3

Anyone who knows how I can achieve this?

谁知道我是怎么做到的?

I've managed to get to this point now (sorry for using other columns, the one above was an example, but I'll guess you'll get the point):

我已经做到了这一点(抱歉用了其他栏目,上面的那篇就是一个例子,但我猜你会明白的):

select distinct
    a.ID,
    a.Name, 
    ca1.NameLine1 as Address1_NameLine1, 
    ca2.NameLine1 as Address2_NameLine1
from 
    dbo.Accounts a, 
    dbo.Addresses ca1,
    dbo.Addresses ca2
where 
        (a.ID = ca1.AccountID AND a.ID = ca2.AccountID)
    AND (a.Name = 'TEST')
    AND (ca1.ID <> ca2.ID)

But I'm still getting 2 rows... where Address1 switches with Address2. Anyone who knows how to only get one? Thanks!

但还是有两行。地址1与地址2交换。谁知道怎么才能得到一个呢?谢谢!

2 个解决方案

#1


4  

Try:

试一试:

select ID,
       max(Name) Name,
       max(case when rn=1 then NameLine1 end) Address1_NameLine1,
       max(case when rn=2 then NameLine1 end) Address1_NameLine2
from
(select a.ID,
        a.Name, 
        ca.NameLine1,
        rank() over (partition by a.ID order by ca.ID) rn
 from dbo.Accounts a 
 join dbo.Addresses ca on a.ID = ca.AccountID
 where a.Name = 'TEST') sq
group by ID

#2


1  

select address1.* ,address2.* from
Address address1 inner join on Address address2
on address1.userid=address2.userid

you can choose inner or left join based on data.

您可以根据数据选择内连接或左连接。

#1


4  

Try:

试一试:

select ID,
       max(Name) Name,
       max(case when rn=1 then NameLine1 end) Address1_NameLine1,
       max(case when rn=2 then NameLine1 end) Address1_NameLine2
from
(select a.ID,
        a.Name, 
        ca.NameLine1,
        rank() over (partition by a.ID order by ca.ID) rn
 from dbo.Accounts a 
 join dbo.Addresses ca on a.ID = ca.AccountID
 where a.Name = 'TEST') sq
group by ID

#2


1  

select address1.* ,address2.* from
Address address1 inner join on Address address2
on address1.userid=address2.userid

you can choose inner or left join based on data.

您可以根据数据选择内连接或左连接。