CTE重复参考

时间:2014-03-26 18:22:21

标签: sql-server common-table-expression hierarchical-data

用于简单的数据结构,例如:

ID    parentID    Name        (Table: VehicleType)
1                 Vehicle
2     1           Small
3     2           Car
4     2           Motorcycle
5     1           Medium
6     5           Pickup

ID    ItemType    Name        (Table: Vehicle)
1     3           Golf
2     4           125

是否可以使用CTE结果:

VehicleType   Name
Vehicle       Golf
Small         Golf
Car           Golf
Vehicle       125
Small         125
Motorcycle    125

我想为每个找到的车型创建寄存器,尝试一切都没有成功。

1 个答案:

答案 0 :(得分:1)

您可以使用递归CTE http://technet.microsoft.com/en-us/library/ms186243(v=sql.105).aspx

;WITH cteRecursiveTypes as
(
    SELECT baseTypeID = t.ID, typeID = t.ID, t.parentID, VehicleType = t.Name, recLevel = 1
    FROM VehicleType t

    UNION ALL

    SELECT t.baseTypeID, parentT.ID, parentT.parentID as parentID, VehicleType = parentT.Name, recLevel = t.recLevel + 1 
    FROM cteRecursiveTypes t
    INNER JOIN VehicleType parentT on t.parentID = parentT.ID

)
SELECT t.VehicleType, v.Name, recLevel = dense_rank() over(partition by t.baseTypeID order by t.recLevel desc) - 1
FROM Vehicle v
INNER JOIN cteRecursiveTypes t on v.ItemType = t.baseTypeID
ORDER BY 2,1
;