我从子查询开始,这样我就可以获得每个特定月份的总销售额。然后,我接受了每个响应并将其嵌套到一个语句中。
然后我创建了主要查询,其中添加了每个月的总数,然后除以5,给出了神秘的月平均销售额。
然后我查询了每个月的总销售额,以便将其与平均值进行比较。
(SELECT
ROUND(SUM(a.total_monthly_sales + b.total_monthly_sales + c.total_monthly_sales + d.total_monthly_sales + e.total_monthly_sales) / 5,
2) AS avg_monthly_sales,
a.total_monthly_sales AS april,
b.total_monthly_sales AS may,
c.total_monthly_sales AS june,
d.total_monthly_sales AS july,
e.total_monthly_sales AS august
FROM
(SELECT
SUM(invoice_total) AS total_monthly_sales,
date_format(invoice_date, '%m-%y') AS 'mm-yy'
FROM
`ap`.`invoices`
WHERE
invoice_date BETWEEN '2011-04-01' AND '2011-04-31') a
JOIN
(SELECT
SUM(invoice_total) AS total_monthly_sales,
date_format(invoice_date, '%m-%y') AS 'mm-yy'
FROM
`ap`.`invoices`
WHERE
invoice_date BETWEEN '2011-05-01' AND '2011-05-31') b
JOIN
(SELECT
SUM(invoice_total) AS total_monthly_sales,
date_format(invoice_date, '%m-%y') AS 'mm-yy'
FROM
`ap`.`invoices`
WHERE
invoice_date BETWEEN '2011-06-01' AND '2011-06-31') c
JOIN
(SELECT
SUM(invoice_total) AS total_monthly_sales,
date_format(invoice_date, '%m-%y') AS 'mm-yy'
FROM
`ap`.`invoices`
WHERE
invoice_date BETWEEN '2011-07-01' AND '2011-07-31') d
JOIN
(SELECT
SUM(invoice_total) AS total_monthly_sales,
date_format(invoice_date, '%m-%y') AS 'mm-yy'
FROM
`ap`.`invoices`
WHERE
invoice_date BETWEEN '2011-08-01' AND '2011-08-31') e)t1
如何才能显示平均值和最接近它的月份?