我是SQL的新手,并尝试以季度粒度计算不同商店的同比销售额。表如下
到目前为止,我有:
SELECT Store_number, SUM(Sales) AS Sales_q1_2018
FROM table1
WHERE Sale_date BETWEEN '2018-01-01' AND '2018-03-31'
GROUP BY Store_number
ORDER BY Sales_Q1_2018
我需要添加一个列,其中包含以下计算:(总和(销售额q1 2018) - 总和(2017年销售额q1))/总和(2017年销售额q1)
如何为临时计算设置不同的日期参数?感谢
答案 0 :(得分:0)
您可以使用子查询来检索2017 q1,将这些连接到您的实际查询
SELECT Store_number, SUM(Sales) AS Sales_q1_2018, (SUM(Sales) - Sales_q1_2107)/Sales_q1_2107
FROM table1
INNER JOIN (
SELECT Store_number, SUM(Sales) AS Sales_q1_2107
FROM table1
WHERE Sale_date BETWEEN '2017-01-01' AND '2017-03-31'
GROUP BY Store_number
) t2 t2.Store_number = table1.Store_number
WHERE Sale_date BETWEEN '2018-01-01' AND '2018-03-31'
GROUP BY Store_number
答案 1 :(得分:0)
试试这个:
SELECT Store_number,
((SUM(IF(year(Sale_date)='2018',Sales,0))
-SUM(IF(year(Sale_date)='2017',Sales,0)))
/SUM(IF(year(Sale_date)='2017',Sales,0))) Q1_2018_vs_2017
FROM table1
WHERE QUARTER(Sale_date)=1 AND YEAR(Sale_date) IN ('2017','2018')
GROUP BY Store_number;
答案 2 :(得分:0)
假设您的宿舍是日历宿舍,我会将查询写为:
SELECT Store_number,
SUM(CASE WHEN YEAR(Sale_date) = 2017 THEN Sales ELSE 0 END) AS Sales_q1_2018,
SUM(CASE WHEN YEAR(Sale_date) = 2018 THEN Sales ELSE 0 END) AS Sales_q1_2017,
(SUM(CASE WHEN YEAR(Sale_date) = 2018 THEN Sales ELSE - Sales END) /
SUM(CASE WHEN YEAR(Sale_date) = 2017 THEN Sales END)
) as calculation
FROM table1
WHERE YEAR(Sale_date) IN (2017, 2018) AND
MONTH(Sale_date) IN (1, 2, 3)
GROUP BY Store_number
ORDER BY Sales_Q1_2018;
Here是SQL小提琴。
这与@ cdaiga的答案类似,但有以下重要区别:
YEAR()
等函数返回数字,因此比较是数字,而不是字符串。CASE
表达式是在查询中包含条件逻辑的ANSI标准方式。 IF()
是特定于MySQL的。0
分割。