SELECT
SUM(b.Amount * (YEAR(b.PayDate) = Years AND (QUARTER(b.PayDate) % 4) + 1 = 1)) AS Q1,
SUM(b.Amount * (YEAR(b.PayDate) = Years AND (QUARTER(b.PayDate) % 4) + 1 = 2)) AS Q2,
SUM(b.Amount * (YEAR(b.PayDate) = Years AND (QUARTER(b.PayDate) % 4) + 1 = 3)) AS Q3,
SUM(b.Amount * (YEAR(b.PayDate) = Years AND (QUARTER(b.PayDate) % 4) + 1 = 4)) AS Q4
FROM
(SELECT
DATE_ADD(sd_date, INTERVAL (Quarter - 1) * 3 MONTH) AS StartDate,
DATE_ADD(DATE_ADD(sd_date, INTERVAL Quarter * 3 MONTH), INTERVAL - 1 DAY) AS EndDate,
Quarter,
YEAR(DATE_ADD(sd_date, INTERVAL (Quarter - 1) * 3 MONTH)) AS Years
FROM
(SELECT DATE_ADD('2014-10-01', INTERVAL - 1 YEAR) AS sd_date) AS sd -- ย้อนหลังไปอีก 1 ปี
CROSS JOIN (SELECT 1 AS Quarter UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4) AS Q) AS ThaiBudgetTable
INNER JOIN Bugget AS b ON (YEAR(b.PayDate) = Years AND (QUARTER(b.PayDate) % 4) + 1 = Quarter) -- 1 = 1
-- WHERE b.customer_id < 1000000
GROUP BY b.ids