我正在尝试连接三个表并将 2 个不同的列连接成多行。当我运行具有多个文件名和多个电话号码的常规查询时,我有四列数据。我想摆脱查询导致的重复项。
我希望不将 id 与不同的文件名重复连接到另一列中,以便 id 用逗号分隔。将所有电话号码与相应的 id 连接成一行并用逗号分隔的情况也是如此。
我发现了一些使用 xml 路径的示例,但它们只有两个表和两列。
下面我有三个表,我到目前为止的查询,以及我希望有的查询。有谁知道在加入表格时如何做嵌套的 xml 路径?
Table: IPMFILE
ID FILENAME
10000.000 10000_45109.doc
10001.000 10001_45115.docx
10002.000 10002_47752.doc
10002.000 10002_45119.doc
10003.000 10003_45123.doc
10004.000 10004_45128.docx
10004.000 10004_45183.docx
表:人员
ID CITY
10000.000 Elkins Park
10001.000 4504 St. James Drive Plano
10002.000 Fort Collins
10003.000 Bound Brook
10004.000 Downers Grove
表:电话
ID 电话
10000.000 215-7177179
10001.000 972-6187143
10002.000 970-4439376
10003.000 家 732-3693106
10004.000 C 630-4648539
60048539 1000481603-
SELECT PERSONS.ID, impfile.FILENAME, phonenumbers.phone, PERSONS.CITY
FROM IMPFILE, Persons, Phonenumbers WHERE impfile.ID=Persons.ID
AND phonenumbers.id=persons.id AND PERSONS.ID
BETWEEN 10000 AND 10004 order by person
Result of Query
ID FILENAME phone CITY
10000.000 10000_45109.doc 215-7177179 Elkins Park
10001.000 10001_45115.docx 972-6187143 4504 St. James Drive Plano
10002.000 10002_47752.doc, 970-4439376 Fort Collins
10002.000 10002_45119.doc 970-4439376 Fort Collins
10003.000 10003_45123 .doc 主页 732-3693106 Bound Brook
10004.000 10004_45128.docx C 630-4648539 Downers Grove
10004.000 10004_45183.docx C 630-4648539 Downers Grove
10004.000 10004_45128.docx H 630-9681673 Downers Grove
10004.000 10004_45183.docx H 630-9681673 Downers Grove
Desired Query with Filename Concatenated for each id and Phone number concatenated for each id and duplicates removed
ID FILENAME phone CITY
10000.000 10000_45109.doc 215-7177179 Elkins Park
10001.000 10001_45115.docx 972-6187143 4504 St. James Drive Plano
10002.000 10002_47752.doc, 10002_45119 .doc 970-4439376 Fort Collins
10003.000 10003_45123.doc Home 732-3693106 Bound Brook
10004.000 10004_45128.docx, 10004_45183.docxC 630-4648539,H 630-9681673 Downers Grove
我在另一篇文章中找到了这个:
SELECT *
FROM ThisTable
OUTER APPLY (SELECT (SELECT SomeField + ' ' AS [data()]
FROM SomeTable
WHERE SomeTable.ID = ThisTable.ID
FOR XML PATH ('')) AS ConcatenatedSomeField) A
OUTER APPLY (SELECT (SELECT SomeField2 + ' ' AS [data()]
FROM SomeTable
WHERE SomeTable.ID = ThisTable.ID
FOR XML PATH ('')) AS ConcatenatedSomeField2) B
OUTER APPLY (SELECT (SELECT SomeField3 + ' ' AS [data()]
FROM SomeTable
WHERE SomeTable.ID = ThisTable.ID
FOR XML PATH ('')) AS ConcatenatedSomeField3) C