聚合相似的行

时间:2013-03-14 13:44:34

标签: aggregate oracle9i

假设我有一个这样的表:

 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和各种聚合函数,但我还没找到我想要的东西。有什么想法吗?

1 个答案:

答案 0 :(得分:1)

假设我在之前的评论中提出的问题是真的,(对于每个NAME,DRCT对,只有空或REF1和REF2的给定值),这似乎有效:

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;

使用union,因为只有一条记录的行不包含在第一个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;