如何进行SQL查询以获取组中的父子数据

时间:2018-04-27 18:57:49

标签: sql-server database sql-server-2012

我有一个客户表,父母和子客户在同一个表中与" ParentId"场关系。表格如下。

CustId      CustName    ParentId
----------------------------------
1           Cust1         0 
2           Cust2         0
3           Sub2Cust1     1
4           Cust3         0
5           Sub1Cust1     1
6           Sub1Cust2     2
7           Sub2Cust2     2
8           Sub4Cust1     1
9           Sub1Cust3     4
10          Sub3Cust1     1

我想要的是来自MS SQL Query,因此它将父记录和子记录保持在一起,如下所示输出:

CustId      CustName    ParentId
----------------------------------
1           Cust1          0 
5           Sub1Cust1      1
3           Sub2Cust1      1
10          Sub3Cust1      1
8           Sub4Cust1      1
2           Cust2          0
6           Sub1Cust2      2
7           Sub2Cust2      2
4           Cust3          0
9           Sub1Cust3      4

任何人都可以给我一个提示如何使用单一查询吗?

提前致谢

2 个答案:

答案 0 :(得分:5)

at_exit do
  if scheduler
    scheduler.shutdown
  end
end

要按名称而不是ID订购孩子,只需改为:

ORDER BY CASE  WHEN ParentId = 0 THEN CustID ELSE ParentId END ASC
,  CASE WHEN ParentId = 0 THEN 0 ELSE CustId END ASC  --to put the parent on top of the children, and keep the children in order

答案 1 :(得分:1)

根据您的评论,您可能需要递归CTE。

技术上不是一个查询,但这将支持变量深度和您想要的排序

示例

;with cteP as (
      Select CustId
            ,ParentId 
            ,CustName 
            ,PathStr = cast(CustName as varchar(max))
      From   YourTable 
      Where  ParentId=0
      Union  All
      Select CustId  = r.CustId
            ,ParentId  = r.ParentId 
            ,CustName   = r.CustName
            ,HierID = P.PathStr+'>'+r.CustName
      From   YourTable r
      Join   cteP p on r.ParentId  = p.CustId )
Select CustId
      ,CustName 
      ,ParentId
 From cteP A
 Order By A.PathStr

<强>返回

CustId  CustName    ParentId
1       Cust1       0
3       Sub1Cust1   1
5       Sub2Cust1   1
8       Sub3Cust    1
10      Sub4Cust1   1
2       Cust2       0
6       Sub1Cust2   2
7       Sub2Cust2   2
4       Cust3       0
9       Sub1Cust3   4