简体   繁体   English

如何显示去年至今的年初至今

[英]How to show YTD last year vs Same period this year

i have this query that is showing me the same period of days from this month 2016 and the same month 2015, 我有这个查询,向我显示了从本月2016年和2015年同月开始的同一天,

But i need to show YTD 但是我需要显示年初至今

Ene, feb, mar, apr, may, jun, up to Jul 6 2015 and same period 2016 (because today is the 6th and tomorrow show 7th then 8th july and so on) Meaning that is something similar to the code i have but instead of showing me just the current month i need YTD. Ene,Feb,Mar,Apr,May,Jun,直到2015年7月6日和2016年同期(因为今天是6日,明天是7月7日,然后是7月8日,依此类推),这意味着与我的代码类似,但是显示我当前需要的月份

SELECT        OrderStatus, Sum_SellPrice, Sum_SellerMargin, Sum_BuyPrice, OrderDate
FROM            Sum_OrderCharges
WHERE        (OrderStatus IN ('Completed', 'Invoiced', 'Open')) 
AND (OrderPeriodYear IN ('2015','2016')) 
AND (MONTH(OrderDate) = MONTH(GETDATE())) 
and (day(OrderDate) <= DAY(GETDATE())) 
ORDER BY OrderDate

Add an OR statement to cover for this: 添加一个OR语句以解决此问题:

OR MONTH(OrderDate) <= MONTH(GETDATE())

SELECT OrderStatus, Sum_SellPrice, Sum_SellerMargin, Sum_BuyPrice, OrderDate
FROM   Sum_OrderCharges
WHERE  OrderStatus IN ('Completed', 'Invoiced', 'Open') 
AND OrderPeriodYear IN ('2015','2016')
AND ( (MONTH(OrderDate) = MONTH(GETDATE()) AND day(OrderDate) <= DAY(GETDATE()))
    OR MONTH(OrderDate) <= MONTH(GETDATE())  )--Be sure to wrap the entire OR segment with ()
ORDER BY OrderDate

It is more elegant to prepare and use date windows using CTE. 使用CTE准备和使用日期窗口更加优雅。 This is an example. 这是一个例子。

declare @start as date='2016-01-01', @end date=getdate(),@depth int = 2

;with dates as (--prepare date ranges
--anchor query
select @start startDate, @end endDate, 1 cnt
union all
--recursive query 
select dateadd(year,-1,startDate),dateadd(year,-1,endDate), cnt+1
from dates where cnt < @depth
)
select d.startDate,d.endDate, 
OrderStatus, Sum_SellPrice, Sum_SellerMargin, Sum_BuyPrice --aggregate if necessary
from Sum_OrderCharges o
inner join dates d on o.OrderDate between d.startDate and d.endDate
WHERE (OrderStatus IN ('Completed', 'Invoiced', 'Open')) 

This way you can even compare date ranges, for example 2015-11-01 to 2016-07-05 and 2014-11-01 to 2015-07-05. 这样,您甚至可以比较日期范围,例如2015-11-01至2016-07-05和2014-11-01至2015-07-05。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM