title: SQL - combining DISTINCT and INNER JOIN and COUNT(CASE WHEN)
body: <p>I have SQL which return me correct result.</p>
  
  <pre><code>select accounts.name, count( case when ((( estimated_start_date&lt;='2013-01-01' 
  and project.status='closed')
  
  or ( estimated_start_date&lt;='2013-01-01' and project.status='open' 
  and estimated_end_date&gt;='2013-04-01')))
  then 1 else null end) as Number
  
  from project
  
  inner join project_cstm on project.id=project_cstm.id_c
  inner join accounts on project_cstm.account_id_c=accounts.id
  
  group by accounts.name
  </code></pre>
  
  <p>I returns me good result:</p>
  
  <p>On example:</p>
  
  <pre><code>Telenor 5
  Telecom 3
  </code></pre>
  
  <p>Now I want to add new field <code>BOOKED_DATE</code> in <code>WHERE</code> clause to restrict number of projects only with some projects tasks created in in that interval. So I do INNER JOIN with table <code>inner join project_task</code> and results should be smaller but instead I am getting as result these huge numbers.Don not know how to combine it.</p>
  
  <p>Thanks for help</p>
  
  <pre><code>Telenor 150
  Telecom 980
  
  select accounts.name, count( case when ((( estimated_start_date&lt;='2013-01-01' 
  and project.status='closed')
  
  or ( estimated_start_date&lt;='2013-01-01' and project.status='open' 
  and estimated_end_date&gt;='2013-04-01')))
  then 1 else null end) as Number
  
  from project
  
  inner join project_cstm on project.id=project_cstm.id_c
  inner join accounts on project_cstm.account_id_c=accounts.id
  inner join project_task on project_task.project_id=project.id
  where booked_date&gt;'2013-01-01' and booked_date&lt;'2015-01-01'
  group by accounts.name
  </code></pre>
  
  <p>Because of rows in table PROJECT_TASK I am getting HUGE results which are far from correct. How to restrict that? I tried putting <code>... count(distinct case when ...</code> but than result is always 1.</p>
  
  <p>So I must somehow restrict this values but instead of that I am </p>