我有2张桌子(公司和联系人)。我需要创建一个所有公司的列表(每个公司ID一行),每个公司ID的所有联系人都在一个单元格中列出,并以公司每个不同联系人的换行符分隔。
我最好在Access中完成这项工作,因为这些表来自访问BE数据库,但如果在MSQL中更容易生成,那么我也可以这样做。
感谢任何提示或解决方案。
答案 0 :(得分:2)
如果这是针对单个列的,那么您可能会发现一篇有趣的文章
https://www.simple-talk.com/sql/t-sql-programming/concatenating-row-values-in-transact-sql/
答案 1 :(得分:0)
对于SQL 2005+,这样的事情可以做到吗?
;with data as
(
SELECT 'Company1' AS company, 'Contact1' AS contact UNION ALL
SELECT 'Company1' AS company, 'Contact2' AS contact UNION ALL
SELECT 'Company1' AS company, 'Contact3' AS contact UNION ALL
SELECT 'Company1' AS company, 'Contact5' AS contact UNION ALL
SELECT 'Company2' AS company, 'Contact1' AS contact UNION ALL
SELECT 'Company3' AS company, 'Contact1' AS contact
)
SELECT
company
,STUFF((
SELECT ',' + contact
FROM data d2
WHERE d2.company = d1.company
FOR XML PATH('')), 1, 1, '') as contacts
FROM data d1
GROUP BY company