将表联接到复杂查询

时间:2018-11-02 21:41:54

标签: sql sql-server

我可以要求别人的帮助来完成MSSMS中的此查询吗?

当前,我有一个查询,可以将ProfileItemID列中的值连接到一行。

这是语法...

     SELECT RoomID, ProfileItemID = 
     STUFF((SELECT DISTINCT ', ' + cast(ProfileItemID AS VARCHAR(10)) FROM 
     RoomProfile b 
     WHERE b.RoomId = a.RoomiD FOR XML PATH('')), 1, 2, '')
     FROM RoomProfile a 
     Where RoomID = 1829
     GROUP BY RoomID

|----------------------------------------|
|                RoomProfile             |
|---------------------|------------------|
|         RoomID      |   ProfileItemID  |
|---------------------|------------------|
|          1829       |         28       |
|---------------------|------------------|
|          1829       |         103      |
|---------------------|------------------|
|          1829       |         104      |
|----------------------------------------|

返回:

+--------+------------+
| RoomID |   Result   |
+--------+------------+
|   1829 | 28,103,104 |
+--------+------------+

现在,我正在尝试将第一个RoomProfile表(上方)与ProfileItem表(下方)连接

|----------------------------------------|
|               ProfileItem              |
|---------------------|------------------|
|     ProfileItemID   |   Description    |
|---------------------|------------------|
|          28         |      Single      |
|---------------------|------------------| 
|          103        |      Double      |
|---------------------|------------------|
|          104        |      Triple      |
|---------------------|------------------|

获得

+------------------------+
|      Description       |
+------------------------+
| Single, Double, Triple |
+------------------------+

我尝试过,但是没有用。

  SELECT ProfileItem.Description = 
  STUFF((SELECT DISTINCT ', ' + cast(ProfileItemID AS VARCHAR(10)) FROM 
  RoomProfile b 
  WHERE b.RoomId = a.RoomiD FOR XML PATH('')), 1, 2, '')
  FROM RoomProfile a 
  INNER JOIN ProfileItem ON 
  RoomProfile a.ProfilteItemID = ProfileItem.ProfileItemID
  Where RoomID = 1829
  GROUP BY RoomID

任何对此的帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

这是基本概念。我没有完全使用您的表名或列名。

DROP TABLE #roomProfiles;
DROP TABLE #profiles;

CREATE TABLE #roomProfiles(RoomId INT, ProfileId INT);
INSERT #roomProfiles VALUES (1829, 28), (1829, 103), (1829, 104);

CREATE TABLE #profiles(ProfileId INT, Description VARCHAR(MAX));
INSERT #profiles VALUES (28, 'Single'), (103, 'Double'), (104, 'Triple');

WITH
    rooms AS (
        SELECT  DISTINCT RoomId 
        FROM    #roomProfiles
    )
SELECT  r.RoomId ,
        STUFF((
            SELECT  DISTINCT ',' + p.Description 
            FROM    #roomProfiles rp 
            INNER JOIN #profiles p 
                    ON p.ProfileId = rp.ProfileId 
            WHERE   rp.RoomId = r.RoomId 
            ORDER BY ',' + p.Description 
            FOR XML PATH('')
            ), 1, 1, '') AS RoomProfiles
FROM    rooms r
ORDER BY r.RoomId