用LEFT连接连接值

时间:2018-07-19 19:23:42

标签: mysql sql left-join

在搜索时,我遇到了非常相似的帖子here 但是我对那里已经发布的内容还有一个疑问。

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尝试了GROUP_CONCAT,但没有帮助。

1 个答案:

答案 0 :(得分:0)

因此,这将导致透视和逗号分隔您的数字,我认为这是理想的效果?这是一个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