如何在 SQL 服务器中找到去年相同的 MTD 日期范围?
How do I find Last year same MTD date range in SQL Server?
我正在尝试查找去年同月的 MTD 数据。谁能帮我找到那个日期范围?
如果我今天提取数据,那么今天的 MTD 将是 4/1/2017 - 4/10/2017 但我正在寻找与去年 4/1/2016 - 4/10 相同的日期范围/2016
这是我今年用 MTD 提出的 SQL 查询,
LEFT JOIN
(SELECT
c2.ID AS CategoryID,
SUM(te.Price * te.Quantity) AS Sales,
SUM(te.Cost * te.Quantity) AS Costs
FROM
TransactionEntry te
LEFT JOIN
Store s ON te.StoreID = s.ID
INNER JOIN
[Transaction] t ON te.TransactionNumber = t.TransactionNumber
AND te.StoreID = t.StoreID
LEFT JOIN
Item i ON te.ItemID = i.ID
LEFT JOIN
Category c2 ON i.CategoryID = c2.ID
WHERE
te.StoreID NOT IN (0, 2, 4, 17, 26)
AND t.Time >= DATEADD(month, DATEDIFF(month, 0, GETDATE()), 0)
AND t.Time < DATEADD(day, DATEDIFF(day, 0, GETDATE()), 1)
GROUP BY
c2.ID) AS mtd
除非你需要更参数化的东西,你可以dateadd -1年:
select DATEADD(year, -1, DATEADD(month, DATEDIFF(month, 0, GETDATE()), 0)),
DATEADD(year, -1, DATEADD(day, DATEDIFF(day, 0, GETDATE()), 1))
输出 2016-04-01 和 2016-04-11
在您查询的上下文中:
WHERE te.StoreID NOT IN (0, 2, 4, 17, 26)
AND t.Time >= DATEADD(year, -1, DATEADD(month, DATEDIFF(month, 0, GETDATE()), 0))
AND t.Time < DATEADD(year, -1, DATEADD(day, DATEDIFF(day, 0, GETDATE()), 1))
我正在尝试查找去年同月的 MTD 数据。谁能帮我找到那个日期范围?
如果我今天提取数据,那么今天的 MTD 将是 4/1/2017 - 4/10/2017 但我正在寻找与去年 4/1/2016 - 4/10 相同的日期范围/2016
这是我今年用 MTD 提出的 SQL 查询,
LEFT JOIN
(SELECT
c2.ID AS CategoryID,
SUM(te.Price * te.Quantity) AS Sales,
SUM(te.Cost * te.Quantity) AS Costs
FROM
TransactionEntry te
LEFT JOIN
Store s ON te.StoreID = s.ID
INNER JOIN
[Transaction] t ON te.TransactionNumber = t.TransactionNumber
AND te.StoreID = t.StoreID
LEFT JOIN
Item i ON te.ItemID = i.ID
LEFT JOIN
Category c2 ON i.CategoryID = c2.ID
WHERE
te.StoreID NOT IN (0, 2, 4, 17, 26)
AND t.Time >= DATEADD(month, DATEDIFF(month, 0, GETDATE()), 0)
AND t.Time < DATEADD(day, DATEDIFF(day, 0, GETDATE()), 1)
GROUP BY
c2.ID) AS mtd
除非你需要更参数化的东西,你可以dateadd -1年:
select DATEADD(year, -1, DATEADD(month, DATEDIFF(month, 0, GETDATE()), 0)),
DATEADD(year, -1, DATEADD(day, DATEDIFF(day, 0, GETDATE()), 1))
输出 2016-04-01 和 2016-04-11
在您查询的上下文中:
WHERE te.StoreID NOT IN (0, 2, 4, 17, 26)
AND t.Time >= DATEADD(year, -1, DATEADD(month, DATEDIFF(month, 0, GETDATE()), 0))
AND t.Time < DATEADD(year, -1, DATEADD(day, DATEDIFF(day, 0, GETDATE()), 1))