我正在尝试编写一个查询来返回当前年份的月初至今数据以及上一年的数据。
这意味着我需要从2017-07-01
到2017-07-26
以及2016-07-01
到2016-07-26
的数据。
但是,我的查询目前会将数据从2017-07-01
返回到2017-07-26
(正确),但也会将数据从2016-07-01
返回到2016-07-31
(错误地)。
如何从两个不同年份获得相同时间段(MTD)的数据?
该表格包括date
,day in quarter
,year
,quarter
,month
和week
,但没有日期列...
SELECT
data_up_to,
date,
year,
month,
sum(sales)
FROM
salesdata.sales
WHERE
MONTH = MONTH(NOW()) and
YEAR in (YEAR(NOW()), YEAR(NOW())-1, YEAR(NOW())-2) and
date <= data_up_to
答案 0 :(得分:0)
我会这样:
SELECT year
, month
, sum(sales)
from salesdata.sales
--Selecting were day in range with same month
WHERE DAY(date) BETWEEN 1 AND DAY(data_up_to)
AND MONTH = MONTH(NOW())
AND YEAR IN (YEAR(NOW()), YEAR(NOW())-1)
--Group by Year, Month
GROUP BY YEAR
, MONTH
如果您想参考NOW()
的MTD,您可以使用:
SELECT year
, month
, sum(sales)
from salesdata.sales
--Selecting were day in range with same month
WHERE DAY(date) BETWEEN 1 AND DAY(NOW())
AND MONTH = MONTH(NOW())
AND YEAR IN (YEAR(NOW()), YEAR(NOW())-1)
--Group by Year, Month
GROUP BY YEAR
, MONTH
我从查询中删除了日期,以便按月和年启用分组。