【问题标题】:How to make SQL query to get parent child data in group如何进行SQL查询以获取组中的父子数据
【发布时间】:2023-03-17 06:02:01
【问题描述】:

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


    【解决方案1】:
    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
    

    【讨论】:

    • 是的,您的查询看起来像部分工作。如果您看到我的输出,我希望父级和子级的 ASC 顺序为 CustName 的输出
    • 我在您的输出中看到的是所有内容都按 ID 排序。如果您希望 CustName 在排序中覆盖 ID,请更改您的示例输出以明确您的意思。此查询将根据您的示例数据生成示例输出。
    • 编辑了我对新输出的回答。
    【解决方案2】:

    根据您的评论,您可能需要递归 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
    

    【讨论】:

    • 是的,CTE 可以提供我想要的输出。但问题是在我的情况下使用的是有很多其他字段并且在该查询中也应用搜索参数,所以我更喜欢如果没有连接的任何单个查询给我输出那么它很好。 @Tab Allemen 查询有效,但唯一的问题是我想要按 ASC 顺序排列的子元素和父元素
    猜你喜欢
    • 2019-04-14
    • 1970-01-01
    • 1970-01-01
    • 2020-12-25
    • 1970-01-01
    • 2022-01-25
    • 1970-01-01
    • 1970-01-01
    • 2011-10-28
    相关资源
    最近更新 更多