查询以创建具有多个表的连续列的视图

时间:2014-03-03 19:35:42

标签: sql sql-server join sql-server-2012 subquery

我有两张三张桌子A,B,C

A                  B                  C

ID   name          ID PID Course      ID PID Nick

1    Mark          1   1  CS           1  3   T
2    John          2   1  AI           2  3   Teddy
3    Ted           3   1  BM           3  2   J
                   4   2  PO           4  1   Mark
                   3   2  MS           5  2   Johnny

我希望视图像

ID   Name   Course     Nick

 1   Mark   CS,AI,BM   Mark
 2   John   PO,MS      J,Johnny
 3   Ted               T,Teddy

这可以使用单个查询吗?

2 个答案:

答案 0 :(得分:2)

SELECT A.ID, A.name,
STUFF(
    (
      SELECT CAST(',' as varchar(max)) + B.Course
      FROM B
      WHERE B.PID = A.ID
      ORDER BY B.Course
      FOR XML PATH('')
    ), 1, 1, '') AS Course,
STUFF(
    (
      SELECT CAST(',' as varchar(max)) + C.Nick
      FROM C
      WHERE C.PID = A.ID
      ORDER BY C.Nick
      FOR XML PATH('')
    ), 1, 1, '') AS Nick
FROM A

答案 1 :(得分:1)

CREATE VIEW vw_MyView
AS
SELECT  A.ID   
       ,A.Name
       ,STUFF((SELECT ', ' + Course
               FROM TABLE_B 
               WHERE PID = A.ID
               FOR XML PATH(''),TYPE).
               value('.','NVARCHAR(MAX)'),1,2,'') AS Courses
       ,STUFF((SELECT ', ' + Nick
               FROM TABLE_C 
               WHERE PID = A.ID
               FOR XML PATH(''),TYPE).
               value('.','NVARCHAR(MAX)'),1,2,'') AS NickName
FROM TABLE_A A 

结果集

╔════╦══════╦════════════╦═══════════╗
║ ID ║ Name ║  Courses   ║ NickName  ║
╠════╬══════╬════════════╬═══════════╣
║  1 ║ Mark ║ CS, AI, BM ║ Mark      ║
║  2 ║ John ║ PO, MS     ║ J, Johnny ║
║  3 ║ Ted  ║ NULL       ║ T, Teddy  ║
╚════╩══════╩════════════╩═══════════╝

WORKING SQL FIDDLE