SQL: Perform Mathematical Operations On Column(s) Before Applying Aggregate Function

Consider a table containing following data.

Date Taxable_Sale Tax_Rate Gross_Amount
2022-01-04 1000 5 1050
2022-02-01 2000 10 2010
2022-03-01 3000 12 3360

Now If I want to perform aggregate function on table to get total sales monthwise, I have written query like this.

SELECT EXTRACT(YEAR_MONTH FROM date) AS month,
       SUM(Gross_Amount) AS totalSales
FROM sales_table
WHERE date between '2022-04-01' AND '2023-03-31'
GROUP BY month
ORDER BY month

Now similarly I want to calculate sum of tax collected for the month, for which a column does not exist in the table. So my question is can I calculate the sum of taxes collected for the month (tax for day is Taxable_Sale * (5/100)) in the same query? How would I go about doing that? Would joins be necessary?

I’ve tried a few different things but unable to get the right solutions. Hence wanting to know if this is possible in single query.

>Solution :

Try this:

SELECT
  EXTRACT(YEAR_MONTH FROM date) AS month,
  SUM(Gross_Amount) AS totalSales,
  SUM(Taxable_Sale * (Tax_Rate / 100)) AS totalTaxes
FROM (
  SELECT
    Date,
    Taxable_Sale,
    Tax_Rate,
    Gross_Amount
  FROM sales_table
  WHERE date BETWEEN '2022-04-01' AND '2023-03-31'
) AS subquery
GROUP BY month
ORDER BY month;

Leave a Reply