递归Teradata查询

时间:2015-05-12 20:39:23

标签: sql recursion teradata recursive-query

我正在尝试将下表查询到合并和排序列表中,例如:

开始列表:

GROUP_ID    MY_RANK EMP_NAME
1   1   Dan
1   2   Bob
1   4   Chris
1   3   Steve
1   5   Cal
2   1   Britt
2   2   Babs
2   3   Beth
3   1   Vlad
3   3   Eric
3   2   Mike

查询结果:

1   Dan, Bob, Steve, Chris, Cal
2   Britt, Babs, Beth
3   Vlad, Mike, Eric

它需要使用递归查询,因为列表要长得多。另外,我必须按my_rank排序才能按顺序排序。提前致谢。我试过在不同的论坛上发现了大约10个例子,但我被困住了。另外,不要担心截断任何尾随/前导逗号。

CREATE TABLE MY_TEST (GROUP_ID INTEGER NOT NULL, MY_RANK INTEGER NOT NULL, EMP_NAME VARCHAR(18) NOT NULL);
INSERT INTO MY_TEST VALUES (1, 1, 'Dan');
INSERT INTO MY_TEST VALUES (1, 2, 'Bob');
INSERT INTO MY_TEST VALUES (1, 4, 'Chris');
INSERT INTO MY_TEST VALUES (1, 3, 'Steve');
INSERT INTO MY_TEST VALUES (1, 5, 'Cal');
INSERT INTO MY_TEST VALUES (2, 1, 'Britt');
INSERT INTO MY_TEST VALUES (2, 2, 'Babs');
INSERT INTO MY_TEST VALUES (2, 3, 'Beth');
INSERT INTO MY_TEST VALUES (3, 1, 'Vlad');
INSERT INTO MY_TEST VALUES (3, 3, 'Eric');
INSERT INTO MY_TEST VALUES (3, 2, 'Mike');

2 个答案:

答案 0 :(得分:3)

你的Teradata版本是什么?是否安装了XML服务?

SELECT * FROM dbc.FunctionsV
WHERE FunctionName = 'XMLAGG';

如果存在此函数,则可以避免递归(无论如何都不是很有效):

SELECT GROUP_ID, 
   TRIM(TRAILING ',' FROM
             CAST(XMLAGG(EMP_NAME || ',' ORDER BY MY_RANK) AS VARCHAR(10000)))
FROM MY_TEST
GROUP BY 1

答案 1 :(得分:0)

这样的事情应该有效:

WITH RECURSIVE employees(Group_ID , Employees, MY_RANK) AS
(
    --Recursive Seed
    SELECT
        GROUP_ID,
        --Cast as a big fat varchar so it can hold all of the employees in a list.
        CAST(EMP_NAME as VARCHAR(5000)),            
        --We need to include MY_RANK so we can choose the next highest rank in the recursive term below.
        MY_RANK 
    FROM
        MY_TEST
    WHERE
        --filter for only my_rank = 1 because that's where we want to start
        MY_RANK = 1

    UNION ALL

    --Recursive Term
    SELECT
        employees.GROUP_ID,
        employees.EMP_NAME || ', ' || MY_TEST.EMP_NAME,
        MY_TEST.MY_RANK
    FROM
        employees
        INNER JOIN MY_TEST ON

            --Joining on Group_id and Rank+1
            employees.GROUP_ID = MY_TEST.GROUP_ID AND
            employees.MY_RANK + 1 = MY_TEST.MY_RANK

)

SELECT GROUP_ID, Employees FROM employees;