'SQL - Error Code: 1064. You have an error in your SQL syntax - WITH

I am struggling because the code i have done is not working

I always get an error with my syntax : "Error Code: 1064. You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SELECT SUM(order_amount) as gms, SUM(order_amount*fees_percentage) as ar, SUM(' at line 2"

This is my code:

WITH totals AS(
    SELECT SUM(order_amount) as gms,
    SUM(order_amount*fees_percentage) as ar,
    SUM(order_amount*(fees_percentage - payment_cost_percentage) as gm, 
        FROM data
        WHERE has_discount > 0
SELECT
gms/SUM(order_amount) AS GMS,
ar/SUM(order_amount*fees_percentage) AS ar,
gm/SUM(order_amount*(fees_percentage - payment_cost_percentage) AS gm, 
FROM data
               LEFT JOIN totals ON data.retailer_id = totals.retailer_id)))

I tried many things but nothing is working, someone can explain me ?

Thank you

Update : I corrected it :

WITH totals AS(
SELECT SUM(order_amount) AS gms,
 SUM(order_amount*fees_percentage) AS ar,
 SUM(order_amount*(fees_percentage - payment_cost_percentage)) AS gm
FROM data
WHERE has_discount > 0)
SELECT
 gms/SUM(order_amount) AS GMS,
 ar/SUM(order_amount*fees_percentage) AS ar,
 gm/SUM(order_amount*(fees_percentage - payment_cost_percentage)) AS gm
FROM data
LEFT JOIN totals ON data.retailer_id = totals.fees_percentage

But now i have an issue with this error : Error Code: 1054. Unknown column 'totals.fees_percentage' in 'on clause'

i don't know how to figure it out



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source