如何根据级别对列进行分组

时间:2018-10-31 07:33:59

标签: sql-server

我有一个表结构和一些示例数据,如下所示。

CREATE TABLE COA
(
COACode NVARCHAR(50),
COATitle VARCHAR(50),
)

INSERT INTO COA VALUES (01, 'Expense');
INSERT INTO COA VALUES (01-01, 'Expense');
INSERT INTO COA VALUES (01-01-01, 'Expense');
INSERT INTO COA VALUES (01-01-02, 'Expense');
INSERT INTO COA VALUES (01-02, 'Expense');
INSERT INTO COA VALUES (01-02-01, 'Expense');
INSERT INTO COA VALUES (01-02-02, 'Expense');

我正在寻找的预期输出是这样的。

COACode     COACode     COACode     COATitle
01                                  Expense
            01-01                   Expense
                        01-01-01    Expense
                        01-01-02    Expense
            01-02                   Expense
                        01-02-01    Expense
                        01-02-02    Expense

查询必须是动态的,例如这是3级COACode,但也可能更多或更少。因此,如果用户插入更高级别的COACode,则应将其插入下一列,但如果它具有相同的COACode级别,则可以。

1 个答案:

答案 0 :(得分:0)

也许你可以这样做

CREATE TABLE COA
(
COACode NVARCHAR(50),
ParentCode NVARCHAR(50),
COATitle VARCHAR(50),
)

INSERT INTO COA VALUES ('01', NULL,'Expense');
INSERT INTO COA VALUES ('01-01', '01','Expense');
INSERT INTO COA VALUES ('01-01-01','01-01' ,'Expense');
INSERT INTO COA VALUES ('01-01-02','01-01', 'Expense');
INSERT INTO COA VALUES ('01-02', '01','Expense');
INSERT INTO COA VALUES ('01-02-01','01-02' ,'Expense');
INSERT INTO COA VALUES ('01-02-02','01-02' ,'Expense');

;WITH x AS
(
    -- anchor:
    SELECT COACode, COATitle, ParentCode, [level] = 0
    FROM COA WHERE ParentCode IS NULL
    UNION ALL
    -- recursive:
    SELECT t.COACode, t.COATitle, t.ParentCode, [level] = x.[level] + 1
    FROM x INNER JOIN COA AS t
    ON t.ParentCode = x.COACode
)
SELECT COACode, COATitle, ParentCode, [level] FROM x
ORDER BY [level]
OPTION (MAXRECURSION 32);