我有一个查询,该查询返回按月分组的销售总额。我想添加一列,该列返回与上一行相比百分比的增长/减少。
我已经尝试使用CREATE TEMPORARY TABLE
,创建变量@var :=
,但实际上没有任何作用。理想情况下,我的结果将是:
Month | Sales | Perc
1 | 100 | 0
2 | 150 | 50
3 | 100 | -33.33
要进行的计算是:((actual_value - previous_value) / previous_value) *100
关于表格,我使用sales
,products
,sales_items
,因此我检索按月分组的销售总额的查询是:
SELECT
MONTH(s.sale_date) AS Month,
SUM(p.retail_price * si.quantity) AS Sales_Amount
FROM sales s
INNER JOIN sales_items si ON s.sale_id = si.sale_id
INNER JOIN products p ON si.product_id = p.product_id
WHERE YEAR(s.sale_date) = '2018'
GROUP BY month
ORDER BY month;
由于我使用SUM
来汇总销售项目并将其汇总到每个sale_id
中,并且按月分组后,使用该值到新列中似乎很复杂,因此如果有人对如何做有想法,那就太好了。
答案 0 :(得分:0)
在MySQL 8.0中,您可以将聚合查询转换为子查询,并使用窗口函数LAG
访问上个月的值,例如:
SELECT
Sales_Month,
Sales_Amount,
( Sales_Amount - LAG(Sales_Amount) OVER(ORDER BY Sales_Month) )
/LAG(Sales_Amount) OVER(ORDER BY Sales_Month) * 100 AS Percent_Increase
FROM (
SELECT
MONTH(s.sale_date) AS Sales_Month,
SUM(p.retail_price * si.quantity) AS Sales_Amount
FROM sales s
INNER JOIN sales_items si ON s.sale_id = si.sale_id
INNER JOIN products p ON si.product_id = p.product_id
WHERE YEAR(s.sale_date) = '2018'
GROUP BY Sales_Month
) x
ORDER BY Sales_Month
答案 1 :(得分:0)
您可以添加新列“ PrevMonthSales”。为此,您必须将查询与自身结合起来:
SELECT ...
FROM
(...your_query...) s1
LEFT JOIN (...your_query...) s2 ON s2.Month = s1.Month - 1
在您的情况下:
SELECT s1.Month, s1.Sales_Amount,
COALESCE(s2.Sales_Amount, 0) "PrevMonthSales",
CASE
WHEN s1.Sales_Amount = 0 THEN 0
ELSE (s1.Sales_Amount - COALESCE(s2.Sales_Amount, 0)) / s1.Sales_Amount
END "Percent"
FROM
(...your_query...) s1
LEFT JOIN (...your_query...) s2 ON s2.Month = s1.Month - 1
答案 2 :(得分:0)
置于名为month_sales的临时表下面
SELECT
MONTH(s.sale_date) AS Month,
SUM(p.retail_price * si.quantity) AS Sales_Amount
FROM sales s
INNER JOIN sales_items si ON s.sale_id = si.sale_id
INNER JOIN products p ON si.product_id = p.product_id
WHERE YEAR(s.sale_date) = '2018'
GROUP BY month
ORDER BY month;
查询以查找月与月之间的差异是:
SELECT *,
case
when m2.Sales_Amount is null then 0
else (m2.Sales_Amount - m1.Sales_Amount)/m1.Sales_Amount
end as Perc
FROM month_sales m1
left Join month_sales m2
WHERE m1.month = m2.month - 1