mysqlsqldatabasesqlyog

SQL - How can I do sum of transactions for certain services (that have different pricing) for each month of the year?


So I had this:

SELECT 
    MONTH(trans_date) AS Month_Booking, 
    count(transact_no) AS NumTransactions, 
    (price * count(transact_no)) AS TotalRevenue
FROM transaction t
JOIN service s ON t.service_no = s.service_no
WHERE YEAR(trans_date) = 2017
GROUP BY MONTH(trans_date)
ORDER BY MONTH(trans_date) asc;

Which returned this result, which is wrong because it doesn't change the price of each service depending on the transaction so the total revenue is wrong here. Result of Query Above

Then I tried this, which is partly complete since it gives me the revenue of one month - which is correct however since it adding different services depending on each transaction.

SELECT 
    sum(TotalRevenue) AS March_Revenue
FROM 
(
    SELECT 
        s.service_no, 
        description, 
        count(transact_no) AS NumTransactions, 
        (price * count(transact_no)) AS TotalRevenue, 
        trans_date
FROM service s
JOIN transaction t ON t.service_no = s.service_no
WHERE MONTH(trans_date) = 3 
AND YEAR(trans_date) = 2017
GROUP BY service_no
ORDER BY service_no asc) March;

Result of Query Above

What I would like, is to have a query that can somehow obtain total revenue for each month, without having to do it individually like this.

Any particular way to do so?

Thanks in advance.


Solution

  • Might be missing something, but I think its just

    SELECT MONTH(trans_date) AS Month_Booking, 
        count(transact_no) AS NumTransactions, 
        sum(price) AS TotalRevenue
    FROM transaction t
    JOIN service s
    ON t.service_no = s.service_no
    WHERE YEAR(trans_date) = 2017
    GROUP BY MONTH(trans_date)
    ORDER BY MONTH(trans_date) asc;