SQL 本月 YTD 和之前的 YTD 数据
SQL Month YTD and prior YTD data
我正在尝试为当前年份和上一年的 return 月初至今数据编写查询。
这意味着我需要从 2017-07-01
到 2017-07-26
以及 2016-07-01
到 2016-07-26
的数据。
但是,我的查询当前 returns 从 2017-07-01
到 2017-07-26
的数据(正确),还有 returns 从 2016-07-01
到 2016-07-31
(错误)。
如何获得两个不同年份的同一时间段 (MTD) 的数据?
table包括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
我从查询中删除了日期以便启用按月和年分组。
我正在尝试为当前年份和上一年的 return 月初至今数据编写查询。
这意味着我需要从 2017-07-01
到 2017-07-26
以及 2016-07-01
到 2016-07-26
的数据。
但是,我的查询当前 returns 从 2017-07-01
到 2017-07-26
的数据(正确),还有 returns 从 2016-07-01
到 2016-07-31
(错误)。
如何获得两个不同年份的同一时间段 (MTD) 的数据?
table包括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
我从查询中删除了日期以便启用按月和年分组。