Skip to content
Advertisement

configure query to bring rows which have more than 1 entries

How to get those entries which have more than 1 records?

If it doesn’t make sense… let me explain:

From the below table I want to access the sum of the commission of all rows where type is joining and “they have more than 1 entry with same downmem_id“.

I have this query but it doesn’t consider more entries scenario…

$search = "SELECT sum(commission) as income FROM `$database`.`$memcom` where type='joining'";

Here’s the table:

id   mem_id   commission   downmem_id   type            time
 2      1       3250            2      joining   2019-09-22 13:24:40
 3      45      500             2      egbvegr        new time
 4      32      20              2      vnsjkdv        other time
 5      23      2222            2      vfdvfvf        some other time
 6      43      42              3      joining        time
 7      32      353             5      joining        time 
 8      54      35              5      vsdvsdd        time

Here’s the expected result: it should be the sum of the id no 2, 7 only ie. 3250+353=whatever.

It shouldn’t include id no 6 because it has only 1 row with the same downmem_id.

Please help me to make this query.

Advertisement

Answer

Another approach is two levels of aggregation:

select sum(t.commission) income
from (select sum(case when type = 'joining' then commission end) as commission
      from t
      group by downmem_id
      having count(*) > 1
     ) t;

The main advantage to this approach is that this more readily supports more complex conditions on the other members of each group — such as at most one “joining” record or both “joining” records and no more than two “vnsjkdv” records.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement