title: SQL: sum of a value but for distinct ids only - conditional sum?
body: <p>I have following structure:</p>
  
  <p>Day with multiple events of typ1 and typ2, where typ1 and typ2 have foreign keys to their respective days. Typ2 also has duration.</p>
  
  <p>Now I want to count all typ1 events, all typ2 events and sum of the typ2 duration.</p>
  
  <p>Example Data:</p>
  
  <p>Day:</p>
  
  <pre><code>ID = 1 | Date = yesterday | ...
  </code></pre>
  
  <p>Typ1:</p>
  
  <pre><code>ID = 1 | FK_DAY = 1 | ...
  
  ID = 2 | FK_DAY = 1 | ...
  </code></pre>
  
  <p>Typ2:</p>
  
  <pre><code>ID = 1 | FK_DAY = 1 | duration = 10
  
  ID = 2 | FK_DAY = 1 | duration = 20
  </code></pre>
  
  <p>I now want the result:</p>
  
  <pre><code>Day.ID = 1 | countTyp1 = 2 | countTyp2 = 2 | sumDurationTyp2 = 30
  </code></pre>
  
  <p>My problem is the sum, I need something like "sum for distinct typ2.ID"... Does anyone know a way to solve that?</p>
  
  <p>I'm using something like the following, but that of course does not work the way I want:</p>
  
  <pre><code>SELECT day.id,
     count( DISTINCT typ1.id ),
     count( DISTINCT typ2.id ),
     sum( duration ) AS duration
  FROM days
     LEFT JOIN typ
            ON day.id = typ1.id
     LEFT JOIN typ2
            ON day.id = typ2.id
  GROUP BY day.id;
  </code></pre>