TSQL +实体框架连接表并将行连接成一个字符串列

时间:2013-04-01 18:59:34

标签: sql sql-server entity-framework tsql

我正在尝试在查询中加入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后,有没有办法通过Entity Framework执行此操作?

2 个答案:

答案 0 :(得分: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

您与外部员工表无关。

答案 1 :(得分:1)

所以,这是半个答案,仅针对您的第一个问题:

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

And here is a demo让你尝试。