0

假设我有一张这样的表:

 NAME   REF1   REF2   DRCT
  A    (null)   Ra     D1
  A      Rb   (null)   D1
  A    (null)   Rc     D2
  B      Rd   (null)   D3
  B    (null)   Re     D3

我想将该表聚合为:

NAME   REF1   REF2   DRCT
 A      Rb     Ra     D1
 A    (null)   Rc     D2
 B      Rd     Re     D3

如您所见,我想聚合具有相同名称的每一行。我搜索了 COALESCE 和各种聚合函数,但没有找到我想要的东西。任何的想法?

4

1 回答 1

1

假设我在之前的评论中问的是真的,(对于每个 NAME、DRCT 对,REF1 和 REF2 仅为 null 或给定值),这似乎有效:

select NAME, M_REF1, M_REF2, DRCT 
from (
    select A.NAME, coalesce(A.REF1, B.REF1) m_REF1, 
       coalesce(A.REF2, B.REF2) m_REF2, A.REF1 A_REF1, B.REF1 B_REF1,
       A.REF2 A_REF2, B.REF2 B_REF2, A.DRCT
    from Table1 A JOIN Table1 B on A.NAME = B.NAME AND A.DRCT = B.DRCT)
    WHERE A_REF1 = m_REF1 AND B_REF2 = m_REF2
UNION
select A.NAME, A.REF1, A.REF2, A.DRCT 
FROM Table1 A JOIN
     (select NAME, DRCT, COUNT(*)
      from Table1
      group by NAME, DRCT
      HAVING COUNT(*) = 1) B ON A.NAME = B.NAME AND A.DRCT = B.DRCT;

使用联合是因为只有一条记录的行不包含在第一个 SELECT 中。

但这有点简单,而且也有效:

select A.NAME, coalesce(A.REF1, B.REF1) M_REF1, coalesce(A.REF2,B.REF2) M_REF2,A.DRCT
from Table1 A LEFT OUTER JOIN Table1 B ON A.DRCT = B.DRCT AND A.NAME = B.NAME 
WHERE NVL2(A.REF1,0,1) = 1 AND NVL2(B.REF1,0,1) =0 
      AND NVL2(A.REF2,0,1) = 0 AND NVL2(B.REF2,0,1) = 1
UNION
select A.NAME, A.REF1, A.REF2, A.DRCT 
FROM Table1 A JOIN
 (select NAME, DRCT, COUNT(*)
  from Table1
  group by NAME, DRCT
  HAVING COUNT(*) = 1) B ON A.NAME = B.NAME AND A.DRCT = B.DRCT;
于 2013-03-14T15:14:10.073 回答