sql-server - 如何进行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
谁能给我一个提示如何使用单个查询来做到这一点?
提前致谢
解决方案
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
推荐阅读
- paypal - 始终为空 paypal IPN 自定义字段
- angular - 如何使用 Angular 7 更改 formGroups 输入元素的日期格式?
- c# - 如何从 ms-access 数据库中导出查询并随后关闭 msaccess.exe 进程?
- javascript - 使用香草承诺的 RSVP 哈希
- javascript - 为离开/关闭页面的用户断开连接
- java - Hibernate search lucene:通过删除子实体来更新索引文档会使子实体成为索引文档中的孤儿
- java - 映射非实体类变量名,如 javax.persistence.metamodel
- c++ - 如何将模板转换为模板 pre C++11
- react-native - 如何在本机反应中禁用文本输入的字体缩放(可访问性的动态类型)?
- c# - ASP.NET Core WebAPI: Bearer error="invalid_token", error_description="找不到签名密钥"