需要根据条件在SQL Server 2008中进行帮助查询

时间:2016-02-25 04:18:35

标签: sql sql-server sql-server-2008

我对SQL Server有疑问

表:Emp

empid | empidref | Name
------+----------+------
 1    |  NULL    |  a
 3    |   1      |  b
 4    |   2      |  c
 2    | NULL     |  d
 5    | NULL     |  e
 6    | NULL     |  f
 8    |  7       |  g 
 7    | NULL     |  h
10    |NULL      |aa

我希望empidref empidempid合并empid值。如果empidref表中有empidref个值,那么相同的empid值视为empid,如果empidref表中没有Empid | Name -------+------ 1 | b 2 | c 5 | e 6 | f 7 |g 10 |aa 值,则需要检索相应的empidref名称相同的empid值视为empid,相应的名称需要检索

基于上表我想要输出如下

viewWillDisappear:

请告诉我如何编写查询以在SQL Server中实现此任务

4 个答案:

答案 0 :(得分:0)

SELECT e1.empid, COALESCE(e2.Name, e1.Name)
FROM Emp e1 LEFT JOIN Emp e2
    ON e1.empid = e2.empidref
WHERE e1.empidref IS NULL

答案 1 :(得分:0)

希望这适合您的要求。

SELECT
 E1.EmpId
,CASE WHEN E2.Name IS NOT NULL
        THEN E2.Name
      ELSE E1.Name
 END AS [Name]
FROM #Emp E1
LEFT OUTER JOIN #Emp E2 ON E1.EmpId = E2.EmpIdRef
WHERE E1.EmpIdRef IS NULL

答案 2 :(得分:0)

正如你所说,你可以像这样编码:

SELECT empidref AS Empid , Name
FROM Emp
WHERE empidref IS NOT NULL
-- Select empidref where it is not null
UNION ALL
-- Merge it with
SELECT empid , Name
FROM Emp
WHERE empidref IS NULL 
-- Select empid where empidref is null
    AND empid NOT IN    (SELECT empidref 
                         FROM Emp 
                         WHERE empidref IS NOT NULL)
-- And empid is not in previous select

另一种方法是使用这样的ROW_NUMBER()

SELECT empid, Name
FROM (
    SELECT COALESCE(empidref, empid) as empid, Name, 
        ROW_NUMBER() OVER (PARTITION BY COALESCE(empidref, empid) ORDER BY empidref DESC) AS seq
    FROM Emp) t
WHERE seq = 1

在上面的查询中我说COALESCE(empidref, empid),因为当empidref为null时,使用empid并为每个COALESCE(empidref, empid)生成一个序列列 - 从1开始 - 按empidref降序排序,以便在null之后变为空值值然后过滤1的序列,因为我首先需要不是空值。

答案 3 :(得分:0)

试试这个,

select isnull(empidref,empid) as empid,name  
from emp  where 
empid not in (select empidref from emp  where empidref is not null)