Domanda

Suppose I've a table like this:

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

I want aggregate this table in something like:

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

As you can see, i want aggregate each row with same name. I've search through COALESCE and various aggregate functions but I haven't found what i was looking for. Any idea?

È stato utile?

Soluzione

Assuming that what I ask in my previous comment is true, (only null or a given value for REF1 and REF2 for each NAME, DRCT pair), this seems to work:

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;

The union is used because the rows with only one record are not included in the first SELECT.

But this is somewhat simpler, and works too:

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;
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top