2013-04-01 49 views
1

我試圖在查詢中連接3個表以獲得彙總員工及其標題的內聚輸出。安裝程序是如下:TSQL +實體框架連接表並將行連接到一個字符串列中

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被修復,是否有辦法通過實體框架來做到這一點?

回答

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 

你沒有關聯到外的員工表。

+0

謝謝HLGEM!現在看看如何在EF中做到這一點。 – Shawn

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給你試用。

+0

感謝拉馬克,HLGEM的回答下面更有道理。感謝sqlfiddle鏈接 - 這非常酷。 – Shawn