Question

Suppose I have 2 tables, query and rank. I would like to know if it is possible to find the sum of minimum values for each query in the rank table?

An entry to the rank table is made only where a user clicks a result for a particular query.

rank (id, key, value) query (id, key, value)

where rank.id = query.id

Snapshot of 5 entries

rank table
-------------
Twp0+x1uZx1Y| Twp1PK8JWhng| 16 
Twp1KU6Pgxp4| Twp1VAF0jRyI| 5
Twp2KuoJWR-8| Twp2OR5X7h78| 1 
Twp354EADhYY| Twp4AQlqjxWg| 2

query table
------------
Twp0+x1uZx1Y| |sap
Twp0-XWZ3gpk| |
Twp1CIP+oh-Q| |
Twp1KU6Pgxp4| |virtual token
Twp14RxuSBzc| |
Was it helpful?

Solution

Use a subquery to join to the query table, like this:

select
    q.id,
    q.key,
    sum(r.minvalue) as valuesum
from
    query q
    left join (select min(value) as minvalue, id from rank group by id) r on
        q.id = r.id
group by
    q.id,
    q.key
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top