简体   繁体   English

用LEFT连接连接值

[英]Concatenate values with LEFT join

While searching, I came across a very similar post here but I have an additional question to what has been posted there already. 在搜索时,我在这里遇到了一个非常相似的帖子但是我对那里已经发布的内容还有一个疑问。

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"

Lets say I want the final result as: 可以说我希望最终结果为:

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"

basically similar results from phone_number concatenated; 连接的phone_number结果基本相似; then can you advise what should I be doing ? 那你能建议我该怎么办? I tried GROUP_CONCAT with DISTINCT but it didn't help. 我用DISTINCT尝试了GROUP_CONCAT,但没有帮助。

So this will pivot and comma delimit your Numbers which I believe is the desired effect? 因此,这将导致透视和逗号分隔您的数字,我相信这是理想的效果? This is a SQL Server solution 这是一个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)

Ouput: 输出:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM