Sql server 如何进行SQL查询以获取组中的父子数据
我有一个客户表,并且父客户和子客户在同一个表中,具有“ParentId”字段关系。下表所示Sql server 如何进行SQL查询以获取组中的父子数据,sql-server,database,sql-server-2012,Sql Server,Database,Sql Server 2012,我有一个客户表,并且父客户和子客户在同一个表中,具有“ParentId”字段关系。下表所示 CustId CustName ParentId ---------------------------------- 1 Cust1 0 2 Cust2 0 3 Sub2Cust1 1 4 Cust3 0 5 Sub1Cust1
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查询,以便它将父记录和子记录保持在一起,如下面的输出:
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
有谁能给我一个提示,如何使用单个查询来完成它
提前谢谢
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
要按名称而不是ID排序子项,只需执行以下操作:
ORDER BY CASE WHEN ParentId = 0 THEN CustID ELSE ParentId END ASC
, CASE WHEN ParentId = 0 THEN '0' ELSE CustName END ASC --to put the parent on top of the children, and keep the children in order
根据您的评论,您可能需要递归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
是的,你看起来像是在工作。如果您看到我的输出,我希望输出为ASC order of CustName for parent and Children。我在您的输出中看到的是,所有内容都是按ID排序的。如果您希望CustName在排序中覆盖ID,请更改您的示例输出,以明确您的意思。此查询将根据您的样本数据生成您的样本输出。已编辑我对新输出的回答。是,使用CTE它将提供我想要的输出。但问题是,在我的例子中使用的是,还有很多其他字段,并且在该查询中也应用了搜索参数,所以我更喜欢没有连接的任何一个查询给我输出,然后它就好了@Tab Allemen查询工作正常,但唯一的问题是子元素和父元素,我希望按ASC顺序排列