K
K
KorsaR-ZN2014-08-27 15:36:36
MySQL
KorsaR-ZN, 2014-08-27 15:36:36

Query with the calculation of the sum of the union table with between?

Good afternoon.
It is necessary to get all auditors who are associated with a certain age group, provided that in their connection the total number in each group is greater (value column of table 3);
The problem is because of table 4, because when combined it gives duplicates to table 2, and from here, with further combining and summation, the sum is obtained, taking into account duplicates, nor grouping on DISTINCT does not remove duplicates. And if you display the result without summation, but with grouping or DISTINCT, then the duplicates disappear, but not when summing. How to be?
1. auditors (auditors)
Its structure is not important here...
2. age groups (audiences)
dfc72290f620472ca971006db4be8333.png
3. age group and auditor relationship map (auditors_audiences_map)
f448e66e24cd4ddf8588eafcd64060ec.png
4. age group disclosures (audiences_range_map)
fccd5558c9954c63874b56a5f1d339d3.png
Examples of requests, with and without grouping..

(
    SELECT am2.id, SUM(am2.value)
    
    FROM auditors_audiences_map AS am2 
    
    LEFT JOIN audiences_range_map AS a2 ON (a2.value BETWEEN 13 AND 17) 
    
    WHERE am2.audience_id=a2.audience_id

    GROUP BY am2.audience_id
)

(
    SELECT am2.id, am2.value
    
    FROM auditors_audiences_map AS am2 
    
    LEFT JOIN audiences_range_map AS a2 ON (a2.value BETWEEN 13 AND 17) 
    
    WHERE am2.audience_id=a2.audience_id

    GROUP BY am2.audience_id
)

execution results:
1. With summation and grouping
c11db67ad1da4f7bba9a0b919bff73dd.png
2. Without summation and grouping
f27b14322b1d43289d8ce9c82cb82711.png
3. Without summation and without grouping
868f7eeecb8b45798081d578bae6c3a7.png
What to do, I don’t understand what the problem is ...
Obviously, when summing, the grouping is not taken into account, but I can’t think of a way to avoid it :(

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
KorsaR-ZN, 2014-08-27
@KorsaR-ZN

I found a solution, I don't know how correct it is, but it works.
If someone has a more correct and optimized version, please tell me, and my solution looks like this:

SELECT SUM(am3.value) FROM 
(
    SELECT am2.id, am2.value
    
    FROM auditors_audiences_map AS am2 
    
    LEFT JOIN audiences_range_map AS a2 ON (a2.value BETWEEN 13 AND 17) 
    
    WHERE am2.audience_id=a2.audience_id

    GROUP BY am2.audience_id
) AS am3

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question