在单列中选择父级和子级

时间:2013-01-02 19:18:28

标签: sql select db2

我目前有这个输出:

ID     Name             Seq
---    -----            ----
82     Morris, Allan    1
82     Morris, Allan    2
82     Morris, Allan    3
82     Morris, Cynthia  1
82     Morris, Shaun    2
82     Morris, Sarah    3

但这是理想的输出:

ID     Name             Seq
---    -----            ----
82     Morris, Allan    0
82     Morris, Cynthia  1
82     Morris, Shaun    2
82     Morris, Sarah    3

这是我当前的查询:

SELECT C.ID AS ID, C.Name AS Name, COALESCE(D.Seq, 0) AS Seq
FROM CMSTR C
LEFT JOIN DMSTR D ON D.ID = C.ID
UNION
SELECT C.ID AS ID, D.Name AS Name, COALESCE(D.Seq, 0) AS Seq
FROM CMSTR C
LEFT JOIN DMSTR D ON D.ID = C.ID

以下是表结构:

CMSTR

ID     Name
---    -----
82     Morris, Allan

DMSTR

ID     Name             Seq
---    -----            ----
82     Morris, Cynthia  1
82     Morris, Shaun    2
82     Morris, Sarah    3

这看起来应该是一个非常简单的查询,但我无法弄清楚如何实现所需的输出。求救!

*的 修改 *

我最初尝试使用以下查询:

SELECT C.ID, (CASE WHEN D.Seq = 0 OR D.Seq IS NULL
                   THEN C.Name
                   ELSE C.Name
              END) AS Name,
       COALESCE(D.Seq, 0) AS Seq
FROM CMSTR C
LEFT JOIN DMSTR D ON D.ID = C.ID

不幸的是,使用上面只返回了从属名称,完全排除了父级。

2 个答案:

答案 0 :(得分:1)

如果我正确理解你的结构(CMSTR每个ID只有1个条目,DMSTR的Seq总是从1开始给定ID),这应该有效:

SELECT ID, Name, 0 AS Seq FROM CMSTR
UNION
SELECT ID, Name, Seq FROM DMSTR
-- ORDER BY ID, Seq - if you want

答案 1 :(得分:0)

如果我理解正确(我真的不知道我是否这样做),这个查询应该能给你你想要的东西:

SELECT  C.ID AS ID, 
        C.Name AS Name, 
        COALESCE(D.Seq-1, 0) AS Seq
FROM CMSTR C
LEFT JOIN ( SELECT ID, MIN(Seq) Seq
            FROM DMSTR
            GROUP BY ID) D 
    ON D.ID = C.ID
UNION
SELECT  ID, 
        Name, 
        Seq
FROM DMSTR