开发者

Flattening SQL server INNER JOIN result [duplicate]

开发者 https://www.devze.com 2023-02-10 07:25 出处:网络
This question already has answers here: Closed 12 years ago. Possible Duplicates: How to return multiple values in one column (T-SQL)?
This question already has answers here: Closed 12 years ago.

Possible Duplicates:

How to return multiple values in one column (T-SQL)?

Simulating group_concat MySQL function in MS SQL Server 2005?

Hi,

Suppose I have 2 tables which i join in which i do a INNER JOIN using a key field.

Schema:

TABLE #a kf int

TABLE #b kf int, data varchar(5)

Now if #a has a single row with value as 1 and #b has multiple rows with the sam开发者_如何学JAVAe key 1 as

  1. 1 DBD
  2. 1 DBE
  3. 1 HDG

Now when i do a join instead of getting 3 rows , Is it possible to get one row with the data values in comma separated manner like

1 DBD,DBE,HDG


Here is a version that use a CTE and XML PATH('')

;with cte as
(
  select
    kf,
    (select data+','
     from #b as b2
     where b1.kf = b2.kf
     for xml path('')) as data
  from #b b1 
  group by kf
)
select
  a.kf, 
  left(b.data, len(b.data)-1) as data
from #a as a
  inner join cte as b
    on a.kf = b.kf
0

精彩评论

暂无评论...
验证码 换一张
取 消