2012-09-28 123 views
3

我有一個麻煩的SQL查詢,我試圖使用 Entrinsik的Informer。我希望Informer對我的 結果執行計算,以使用javascript製作一個百分比。但是,Informer沒有 訪問數據列的能力(即我的總數爲 百分比),所以我需要我的SQL查詢爲我生成這個數據。結果 目前看起來是這樣的:使用MySQL/Javascript計算百分比

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

我想什麼是這樣的:

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 

我的查詢如下:

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 

併產生第二查詢每月總計表如下所示:

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 

那麼有什麼方法可以將兩者結合?

回答

1

你在技術上可以從字面上加入這兩個子查詢。

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 

只要確保你在爲「month_total」或類似名稱的「總的查詢」重命名「REFUND_AMOUNT」。