首页 > 解决方案 > 如何进行SQL查询以获取组中的父子数据

问题描述

我有一个客户表,并且在同一个表中有父客户和子客户,并且具有“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

谁能给我一个提示如何使用单个查询来做到这一点?

提前致谢

标签: sql-serverdatabasesql-server-2012

解决方案


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

推荐阅读