选择“值”并将该查询的结果用作下一个查询中的“选择项”

时间:2015-10-23 20:55:45

标签: sql sql-server tsql

我不确定如何说出来。我觉得我对SQL有很好的理解,但我很难过。

背景知识。

我有一个表该表上的CustomersGroups存在def replace(stringname,oldletter,newletter): newstring = '' for i in range(len(stringname)): if stringname[i] == oldletter: newstring = newstring + newletter else: newstring = newstring + stringname[i] return newstring stringorig = "Hello World!" displayname = replace(stringorig,'l','o') print displayname

客户可以创建树组结构。

GroupName, GroupId, ParentGroupId, ObjectRowState

如果用户删除了一个组,则删除所有子组关联。我希望能找到一个小组。然后在查询中使用该组作为其子组的父组ID,依此类推..

所以

parent
-Child
- - GrandChild
- - GreatGrandChild
etc. 

结果SELECT * FROM tbl_CustomersGroups WHERE CompanyId = 123 And GroupName = North

GroupID = 111

给孩子SELECT * FROM Tbl_CustomersGroups WHERE ParentGroupID = 111

带来了结果

然后我想让这个查询一遍又一遍,直到没有剩下的组为止。通常有6个等级。

而不是一遍又一遍地进行单独的查询,我想要一个大的查询,我可以在其中放入ParentGroupID,它将循环并给我所有的孩子。

我不是要求写一个查询,我要求指导或示例如何解决这个问题。

1 个答案:

答案 0 :(得分:0)

我希望这可以帮到你。你需要使用CTE(公用表表达式) https://technet.microsoft.com/en-us/library/ms186243(v=sql.105).aspx

CREATE TABLE #table (GroupName varchar(50), 
                     GroupId int, 
                     ParentGroupId int, 
                     ObjectRowState varchar(50))

insert into #table values ('vehicle', 1, null, 'general vehicle')
insert into #table values ('Car', 2, 1, 'general cars')
insert into #table values ('2 doors car', 3, 2, 'cars with 2 doors')
insert into #table values ('4 doors car', 4, 2, 'cars with 4 doors')
insert into #table values ('Motorcycle', 5, 1, 'general Motorcycle')
insert into #table values ('Speed Motorcycle', 6, 5, 'Speed Motorcycle')
insert into #table values ('Road Motorcycle', 7, 5, 'Road Motorcycle')
insert into #table values ('Truck', 8, 1, 'General Truck')
insert into #table values ('Waggon', 9, 8, 'General Truck')
insert into #table values ('Airplane', 10, null, 'General Airplane')
insert into #table values ('Jet Airplane', 11, 10, 'General Jet Airplane')
insert into #table values ('Jet Fighter', 12, 11, 'General Jet Airplane')

;with cte (GroupName , GroupId , ParentGroupId , ObjectRowState, Grouplevel, RowOrder)
AS
(
    SELECT GroupName, 
           GroupId, 
           ParentGroupId, 
           ObjectRowState, 
           1, 
           ROW_NUMBER() OVER (ORDER BY GroupId)
    FROM #table
    WHERE ParentGroupId IS NULL
    UNION ALL
    SELECT #table.GroupName, 
           #table.GroupId, 
           #table.ParentGroupId, 
           #table.ObjectRowState, 
           cte.Grouplevel + 1, 
           cte.RowOrder
    FROM #table
    INNER JOIN cte on cte.GroupId = #table.ParentGroupId

)
SELECT GroupName, 
       GroupId, 
       ParentGroupId, 
       ObjectRowState 
FROM cte 
ORDER BY cte.RowOrder, cte.Grouplevel

DROP TABLE #table