0

我目前有这个输出:

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

不幸的是,使用上述仅返回依赖名称,完全不包括父名称。

4

2 回答 2

1

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

SELECT ID, Name, 0 AS Seq FROM CMSTR
UNION
SELECT ID, Name, Seq FROM DMSTR
-- ORDER BY ID, Seq - if you want
于 2013-01-03T21:45:00.497 回答
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 
于 2013-01-02T19:25:16.220 回答