我正在尝试编写一个查询来返回当前年份和上一年的当月至今数据。
这意味着我需要从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
我会这样说:
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
我从查询中删除了日期,以便按月份和年份进行分组。