SQL加入子记录

时间:2014-04-04 08:23:29

标签: sql sql-server

我正在为父客户端记录的SQL连接而奋斗(字面意思是在我的例子中!)。我的数据库表由(例如非常通用的例子)组成。

Table Room
Room No
  1
  2
  3

Table Customer
| Customer ID | Customer Name       | Associated
|   1        |    Joe Bloggs        |  
|   2        |    Little Bloggs     | 1
|   3        |    Little bloggs pet | 2

Table Bookings
| Room No | Customer |
| 1       |    1     |

我所追求的是一些SQL来获取完整的3个等级和空间,例如。

Room   Customer
1      Joe Bloggs
1      Little Bloggs
1      Little Bloggs pet

客户2和3没有直接加入,但它们通过客户1继承到1号房间。

3 个答案:

答案 0 :(得分:2)

您应该可以使用递归CTE来完成此操作。

如下所示

;WITH Vals AS (
        SELECT  CustomerID,
                CustomerName,
                b.Room
        FROM    Customer c INNER JOIN
                Bookings b  ON  c.CustomerID = b.Customer
        UNION ALL
        SELECT  c.CustomerID,
                c.CustomerName,
                v.Room
        FROM    Vals v INNER JOIN
                Customer c  ON  c.Associated = v.CustomerID
)
SELECT  *
FROM    Vals

答案 1 :(得分:1)

;with Cte (RoomId,Name ,CustomerId)
as(
   Select R.RoomId,C.Name,C.CustomerId
    From Booking B
     Inner Join Customer C on C.CustomerId=B.Customer
     Inner Join Room R On R.RoomId=B.RoomNo
    Union All
    Select Cte.RoomId,Cus.Name,Cus.CustomerId
    From Customer Cus
        inner join Cte On Cte.CustomerId=Cus.Associated
)

Select RoomId,Name  from Cte

了解更多Recursive Queries Using Common Table Expressions

答案 2 :(得分:0)

您可以使用CTE执行此操作,请查看SQLFiddle以获取示例

下面提供了CTE部分,请注意,已将 Associated 重命名为 AssociatedCustomerID 以使其更有意义:

    WITH CTE AS
(   SELECT  *, 0 [Level]
    FROM    Customer
    UNION ALL
    SELECT  CTE.CustomerID, CTE.CustomerName, Customer.AssociatedCustomerID, Level + 1
    FROM    CTE
            INNER JOIN Customer
                ON CTE.AssociatedCustomerID = Customer.CustomerID
    WHERE   Customer.AssociatedCustomerID IS NOT NULL
)

SELECT  c.CustomerID, c.CustomerName, c.AssociatedCustomerID AssociatedCustomerID , Bookings.RoomID
FROM    (   SELECT  *, MAX([Level]) OVER (PARTITION BY CustomerName) [MaxLevel]
            FROM    CTE
        ) c
INNER JOIN Bookings on ISNULL(c.AssociatedCustomerID,c.CustomerID) = Bookings.CustomerID
WHERE   MaxLevel = Level