gpt4 book ai didi

SQL Server 字符串连接与东西

转载 作者:行者123 更新时间:2023-12-04 00:20:46 24 4
gpt4 key购买 nike

我已经在网上看了几天如何在 sql server 上使用 STUFF,我看到的大多数示例只涉及两个表,而我的查询要遍历 3 个表,但我无法让它工作这是没有 STUFF 函数的查询,它为我提供了我想要的所有数据:

select c.category_name,r.role_name
from categories as c
join role_categ as rc on c.category_id=rc.category_id
join roles as r on r.role_id=rc.role_id
where rc.c_read='1';

These are the results

我想要的是你有一个 Category_name 然后我想要第一行的一个单元格中的所有 role_names 例如:

BCM-Télécopieur-photocopieur Admin,Administation

Here what I have with the stuff function but doesnt work jsut gives me the same table as the other query

select c.category_name,STUFF((
select ','+r.role_name
from roles as r
where rc.role_id=r.role_id
for xml path('')),1,1,'')
from role_categ as rc
join categories as c on c.category_id=rc.category_id

如有任何帮助,我们将不胜感激。

最佳答案

这是我想出的一个版本。 @GiorgosBetsos 是正确的,JOIN 需要移动到内部查询。我不确定为什么他仍然看到重复项,但以下查询按预期返回数据:

-- Set up the data
DECLARE @roles TABLE (role_id INT, role_name VARCHAR(20))
DECLARE @role_categories TABLE (category_id INT, role_id INT)
DECLARE @categories TABLE (category_id INT, category_name VARCHAR(20))

INSERT INTO @roles (role_id, role_name) VALUES (1, 'Admin'), (2, 'Administration'), (3, 'Tech')
INSERT INTO @categories (category_id, category_name) VALUES (1, 'Consultant'), (2, 'FTP'), (3, 'Logicals')
INSERT INTO @role_categories (category_id, role_id) VALUES (1, 1), (1, 2), (1, 3), (2, 1), (2, 3), (3, 1)

-- The query
SELECT
C.category_name,
STUFF((
SELECT ',' + R.role_name
FROM
@role_categories RC
INNER JOIN @roles R ON R.role_id = RC.role_id
WHERE
RC.category_id = C.category_id AND
RC.c_read = 1
FOR XML PATH('')), 1, 1, '')
FROM
@categories C

关于SQL Server 字符串连接与东西,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35869258/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com