Search code examples
sqlsqlitesubqueryaggregation

How to aggregate a specific set of results with the matching set of results


here a 2 outputs of two queries:

output 1:

duration               | allWorkItems
-----------------------+------
 between 15 and 60 min | 56
 bigger than 60 min    | 39

output 2:

duration               | finishedWorkItems
-----------------------+------
 between 15 and 60 min | 19
 bigger than 60 min    | 28

Now I want to divide the "finishedWorkItems" with "allWorkItems" to get a percentage. So in simplified code:

SELECT CASE 
WHEN strftime('%s', end) - strftime('%s', beginning) < 15*60 THEN 'smaller than 15 min'
WHEN  strftime('%s', end) - strftime('%s', beginning) BETWEEN 15*60 AND 60*60 THEN 'between 15 min and 60 min'
ELSE 'more than 60 min' END AS duration,
**(COUNT(task_id WHERE finished = true)/COUNT(task_id)) finishingRate**
FROM 
[..](I think the query would be too long)
GROUP BY 1

I have tried to solve this via a subquery. However this doesn't work and it's awfully bad readable. Has anyone an idea to solve this problem?

The result in this example should be:

duration               | finishingRate
-----------------------+------
 between 15 and 60 min | 0,33
 bigger than 60 min    | 0,71

Solution

  • How about join?

    with q1 as (< query 1 here>),
         q2 as (< query 2 here>)
    select q1.duration, q2.finishedWorkItems / q1.finishedWorkItems
    from q1 join
         q2
         on q1.duration = q2.duration;