多列而不是1列

时间:2015-09-15 00:33:41

标签: sql

我试图列出一系列3个表的多个列,它可以识别单个房屋的多个所有者,但是我试图弄清楚要搜索什么来帮助我完成我的工作#39;我正在寻找。

Inventory
--------------------
ID | House Address |
--------------------
1  | 123 Main St   |
--------------------
2  | 436 East St   |
--------------------

Contacts
----------------
ID | Name      |
----------------
1  | Billy Bob |
----------------
2  | Mary Ann  |
----------------
3  | Gilligan  |
----------------
4  | Skipper   |
----------------

Owners
-----------------------
InvID  |  ContactsID  |
-----------------------
1      | 2            |
-----------------------
2      | 1            |
-----------------------
2      | 3            |
-----------------------
2      | 4            |
----------------------- 

Ideal Result
----------------------------------------------
Address     | Owner1    | Owner2   | Owner3  |
----------------------------------------------
123 Main St | Billy Bob | Gilligan | Skipper |
----------------------------------------------
436 East St | Mary Ann  |          |         |
----------------------------------------------

我已经尝试加入这些表但是它没有给出预期的输出。如果有人能指出我的研究方向,我很乐意自己找到答案,但此时我正在为我正在寻找的东西挠头。

我尝试过的一个解决方案:

Select 
    Inventory.Address,
    Contacts.FirstName + ' ' + Contacts.LastName AS 'Owner',
    Contacts.Phone
From Inventory
LEFT JOIN Owners
ON Owners.InventoryID = Inventory.ID
LEFT JOIN Contacts
ON Contacts.ID = Owners.ContactID

这给了我所需的所有信息,而不是我希望实现的格式。

1 个答案:

答案 0 :(得分:1)

使用嵌套派生表考虑以下查询,该表使用计算出的行号在单独的列中显示Owners 1-3。

这应该作为大多数RDMS的通用解决方案,因为它使用的ANSI SQL语法不限于任何特定的unstashPivot()Over()函数:

CTE()

输出如下:

SELECT 
   Address, 
   Max([Owner_1]) As Owner1,
   Max([Owner_2]) As Owner2,
   Max([Owner_3]) As Owner3
FROM
  (SELECT Address,
         CASE RowNumber = 1 THEN [Name] END As Owner_1,
         CASE RowNumber = 2 THEN [Name] END As Owner_2,
         CASE RowNumber = 3 THEN [Name] END As Owner_3
  FROM 
       (SELECT Owners.InvID, Owners.[Contacts ID], Inventory.Address, Contacts.Name,
              (SELECT Count(*) FROM Owners t1 
               WHERE t1.[Contacts ID] <= Owners.[Contacts ID] 
               AND t1.InvID = Owners.InvID) As RowNumber    
       FROM Owners 
       LEFT JOIN Inventory ON Owners.InvID = Inventory.ID 
       LEFT JOIN Contacts ON Owners.[Contacts ID] = Contacts.ID
  ) As dT1
) As dt2
GROUP BY Address;