我正在尝试在查询中加入 3 个表,以获得总结员工及其职位的连贯输出。设置如下:
CREATE TABLE employees (id INT, name VARCHAR(16))
CREATE TABLE titles (employeeId INT, standardTitleId INT)
CREATE TABLE standard_titles(standardTitleId INT, title VARCHAR(16))
GO
INSERT INTO standard_titles VALUES
(0, 'Co-Founder'),
(1, 'CEO'),
(2, 'CTO'),
(3, 'CFO')
INSERT INTO employees VALUES
(0, 'Bill'),
(1, 'Bob'),
(2, 'Sue')
INSERT INTO titles VALUES
(0, 0),
(0, 1),
(1, 0),
(1, 2),
(2, 3)
GO
我想要的输出是这样的:
id name titles
================================
0 Bill Co-Founder, CEO
1 Bob Co-Founder, CTO
2 Sue CFO
通读帖子后,我设法接近但也设法解决了一些问题:
SELECT
e.id,
e.name,
STUFF((
SELECT ', ' + s.title
FROM standard_titles s
INNER JOIN titles t ON t.standardTitleId = s.standardTitleId
INNER JOIN employees e ON e.id = t.employeeId
WHERE t.standardTitleId = s.standardTitleId
FOR XML PATH ('')), 1, 1, '')
FROM employees e
这给了我这个:
id name (No column name)
===========================================================
0 Bill Co-Founder, CEO, Co-Founder, CTO, CFO
1 Bob Co-Founder, CEO, Co-Founder, CTO, CFO
2 Sue Co-Founder, CEO, Co-Founder, CTO, CFO
问题:
我在这
FOR XML PATH
部分做错了什么。一旦 TSQL 被修复,有没有办法通过实体框架来做到这一点?