我有两个名为Districts
和Schools
的表。 Districts
表包含名为Schools
的列。
我需要从相应的Schools
表填充Districts
表的Schools
列,以便Districts
表中的每一行都有逗号分隔的列表Schools
表中的学校名称值。
我该怎么做?我应该使用UPDATE
查询还是存储过程?
我只有:
Districts Table
+------------+------+---------+
| DistrictId | Name | Schools |
+------------+------+---------+
| 1 | a | |
| 2 | b | |
| 3 | c | |
| 4 | d | |
+------------+------+---------+
Schools Table
+----------+------------+------------+
| SchoolId | SchoolName | DistrictId |
+----------+------------+------------+
| 1 | s1 | 1 |
| 2 | s2 | 1 |
| 3 | s3 | 2 |
| 4 | s4 | 2 |
| 5 | s5 | 4 |
+----------+------------+------------+
输出需要
+------------+------+---------+
| DistrictId | Name | Schools |
+------------+------+---------+
| 1 | a | s1,s2 |
| 2 | b | s3,s4 |
| 3 | c | |
| 4 | d | s5 |
+------------+------+---------+
答案 0 :(得分:6)
借助FOR XML PATH
和 STUFF 来协调这些值,您可以轻松地使用所需结果更新表格District
。
UPDATE a
SET a.Schools = b.SchoolList
FROM Districts a
INNER JOIN
(
SELECT DistrictId,
STUFF((SELECT ', ' + SchoolName
FROM Schools
WHERE DistrictId = a.DistrictId
FOR XML PATH (''))
, 1, 1, '') AS SchoolList
FROM Districts AS a
GROUP BY DistrictId
) b ON A.DistrictId = b.DistrictId
WHERE b.SchoolList IS NOT NULL