sql server combines multiple rows of data and displays them in one row

In SQL Server, you can use STUFF and FOR XML PATH to merge multiple rows into one row. For example, assume there is a table named sys_role_permission that contains role_id and role_permission_id:

The following query will group on the role_id column, combining role_permission_id into a single row:

SELECT role_id, STUFF((SELECT ', ' + permission_id
                        FROM sys_role_permission o2
                        WHERE o2.role_id = o1.role_id
                        FOR XML PATH('')), 1, 2, '') AS permission_id
FROM sys_role_permission o1
GROUP BY role_id

In the STUFF function, the first parameter specifies the position to be inserted, the second parameter specifies the number of characters to be deleted starting from the position specified by the first parameter, and the third parameter specifies the new value to be inserted. In this query, use FOR XML PATH to convert each product name to a comma-separated string, and then use STUFF to remove the first comma and combine all product names into a single string. Finally, use GROUP BY to group based on the role_id column.

Guess you like

Origin blog.csdn.net/zgscwxd/article/details/134855870