user1706938
user1706938

Reputation: 131

Calculate percentages with MySQL/Javascript

I have a troublesome SQL query that I'm trying to make using Entrinsik's Informer. I want Informer to perform a calculation on my result to make a percentage using javascript. However, Informer lacks the ability to access data down columns (i.e. my total for the percentage) so I need my SQL query to generate this for me. The result currently looks like this:

refund_code    refund_amount    month_group
-----------    -------------    -----------
ref1               10           january
ref2               20           january
ref3               30           january
ref1               40           february
ref2               50           february
ref3               60           february

What I would like is something like this:

refund_code    refund_amount    month_group    month_total  
-----------    -------------    -----------    -----------  
ref1               10           january                 60  
ref2               20           january                 60  
ref3               30           january                 60  
ref1               40           february               150  
ref2               50           february               150  
ref3               60           february               150  

My query is as follows:

SELECT mr.month_group,
    bd.transaction_code AS refund_code,
    SUM(bd.extended) AS refund_amount
FROM   billing_details AS bd
    LEFT JOIN monthly_ranges AS mr
        ON ( bd.entry_date BETWEEN mr.start_date AND mr.end_date )
WHERE  bd.transaction_code IN ( 'REFPRI', 'REFSEC', 'REFPT', 'REFREQPRI' )
    AND bd.entry_date >= '2012-01-05'
GROUP BY mr.month_group, bd.transaction_code
ORDER BY mr.month_group, bd.transaction_code

And a second query to produce a table of totals per month looks like this:

SELECT mr.month_group,
    SUM(bd.extended) AS refund_amount
FROM   billing_details AS bd
    LEFT JOIN monthly_ranges AS mr
        ON ( bd.entry_date BETWEEN mr.start_date AND mr.end_date )
WHERE  bd.transaction_code IN ( 'REFPRI', 'REFSEC', 'REFPT', 'REFREQPRI' )
    AND bd.entry_date >= '2012-01-05'
GROUP BY mr.month_group
ORDER BY mr.month_group

So is there any way to combine the two?

Upvotes: 3

Views: 335

Answers (1)

dispake
dispake

Reputation: 3329

You technically could literally join the two as subqueries.

i.e.

SELECT m.refund_code, m.refund_amount, m.month_group, t.month_total
 FROM (your refund query above) m
 JOIN (your total query above) t
   ON m.month_group = t.month_group

Just make sure you rename 'refund_amount' in your 'total query' to 'month_total' or something similar.

Upvotes: 1

Related Questions