用左连接连接值

kuarbcqp  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(435)

在搜索的时候,我在这里遇到了一个非常类似的帖子,但是我还有一个问题,那就是已经在那里发布了什么。

id|person_name|department_name|phone_number
--+-----------+---------------+------------
1 |"John"     |"Finance"      |"023451"
1 |"John"     |"Finance"      |"99478"
1 |"John"     |"Finance"      |"67890"
1 |"John"     |"Marketing"    |"023451"
1 |"John"     |"Marketing"    |"99478"
1 |"John"     |"Marketing"    |"67890"
2 |"Barbara"  |"Finance"      |""
3 |"Michelle" |""             |"005634"

假设我希望最终结果是:

id|person_name|department_name|phone_number
--+-----------+---------------+------------
1 |"John"     |"Finance"      |"023451", "99478", "67890"
1 |"John"     |"Marketing"    |"023451", "99478", "67890"
2 |"Barbara"  |"Finance"      |""
3 |"Michelle" |""             |"005634"

基本相似的结果来自 phone_number 串联的;那你能告诉我该怎么办吗?我试过用distinct来分组,但没用。

lndjwyie

lndjwyie1#

所以,这将轴心和逗号分隔您的数字,我相信这是理想的效果?这是一个sql server解决方案

declare @t table (OrderedID int, EmpName varchar(50), EmpDep varchar(50), Num varchar(50))

insert into @t
values
(1,'John','Dep1','123')
,(1,'John','Dep1','456')
,(1,'John','Dep2','789')
,(2,'Doug','Dep1','987')
,(2,'Doug','Dep1','654')
,(2,'Steve','Dep2','321')

Select

* 

From @t

SELECT distinct e.EmpName,
  e.EmpDep,
  LEFT(r.Num , LEN(r.Num)-1) num
FROM @t e
CROSS APPLY
(
    SELECT r.Num + ', '
    FROM @t r
    where e.EmpName = r.EmpName
      and e.EmpDep = r.EmpDep
    FOR XML PATH('')
) r (Num)

输出:

EmpName EmpDep  num
Doug    Dep1    987, 654
John    Dep1    123, 456
John    Dep2    789
Steve   Dep2    321

相关问题