1

我正在尝试在查询中加入 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

问题:

  1. 我在这FOR XML PATH部分做错了什么。

  2. 一旦 TSQL 被修复,有没有办法通过实体框架来做到这一点?

4

2 回答 2

2

所以,这里有一半的答案,只针对你的第一个问题:

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 e.id = t.employeeId
        FOR XML PATH ('')), 1, 1, '')
FROM employees e

这是一个演示供您尝试。

于 2013-04-01T19:07:52.797 回答
1

尝试这个:

SELECT
    e.id,
    e.name, 
    STUFF((
        SELECT ', ' + s.title
        FROM standard_titles s
            INNER JOIN titles t ON t.standardTitleId = s.standardTitleId
        WHERE e.id = t.employeeId
        FOR XML PATH ('')), 1, 1, '')
FROM employees e

您没有与外部员工表相关联。

于 2013-04-01T19:05:29.490 回答