我目前有这个输出:
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
不幸的是,使用上述仅返回依赖名称,完全不包括父名称。