Mysql
 sql >> Database >  >> RDS >> Mysql

Fare alcune somme abbastanza semplici con tabelle diverse

Un approccio potrebbe essere quello di utilizzare le viste in linea. Per farlo

  • Crea una query che somma i punti guadagnati
  • Crea una query che somma i punti spesi
  • Unisci le query insieme (un join sinistro nel caso non abbiano ancora speso nulla)
  • Fai la tua sottrazione


SELECT SumOfPointsEarned.Points - COALESCE(SumOfPointsOfPurchasesMade.Points, 0) AS CurrentPoints
FROM   
(
    SELECT SUM(Points) AS Points, Recipient_ID 
    FROM   transactions 
            WHERE Recipient_ID= 137642
    GROUP  BY Recipient_ID
) AS SumOfPointsEarned 
    LEFT JOIN 
    (
        SELECT purchases.Student_ID,  SUM(rewards.Cost_to_User) AS Points 
        FROM   purchases 
            INNER JOIN rewards 
            ON purchases.Reward_ID = rewards.Reward_ID 
                    WHERE Student_ID = 137642
        GROUP  BY purchases.Student_ID
    ) AS SumOfPointsOfPurchasesMade 
    ON SumOfPointsEarned.Recipient_ID = SumOfPointsOfPurchasesMade.Student_ID