不确定您使用的是什么 RDMS,但这应该可以解决问题。datepart 和 dateadd 的东西是 tsql 特定的,但我假设您可以在您使用的任何平台上访问类似的功能。where 中的大小写决定了使用哪个年份值。
回答:
select c.companyid
,yearendingdate + '/' + convert(varchar, datepart(yy, dateadd(yy,1,o.orderdate))) as yearending
,sum(ordervalue) as numberoforders
from @orders o
join @companies c
on o.companyid = c.companyid
where orderdate between case when (cast(yearendingdate + '/' + convert(varchar, datepart(yy, o.orderdate)) as datetime) >= o.orderdate)
then yearendingdate + '/' + convert(varchar, datepart(yy, dateadd(yy,-1,o.orderdate)))
else yearendingdate + '/' + convert(varchar, datepart(yy, o.orderdate))
end
and
case when (cast(yearendingdate + '/' + convert(varchar, datepart(yy, o.orderdate)) as datetime) >= o.orderdate)
then yearendingdate + '/' + convert(varchar, datepart(yy, o.orderdate))
else yearendingdate + '/' + convert(varchar, datepart(yy, dateadd(yy,1,o.orderdate)))
end
group by c.companyid, o.orderdate, yearendingdate
找出问题的代码:
declare @orders table (OrderDate datetime
,CompanyID varchar(20)
,OrderValue int)
insert into @orders
values (getdate(),'MS',2)
insert into @orders
values (DateAdd(year, -1, getdate()),'MS',3)
insert into @orders
values (DateAdd(year, -1, getdate()),'MS',1)
insert into @orders
values (DateAdd(year, 1, getdate()),'MS',4)
insert into @orders
values (DateAdd(year, 1, getdate()),'Blizzard',2)
insert into @orders
values (getdate(),'MS',11)
declare @companies table (CompanyID varchar(20)
,YearEndingDate varchar(20))
insert into @companies
values ('MS', '05/6')
insert into @companies
values ('Blizzard', '07/01')
select c.companyid
,o.orderdate
,yearendingdate + '/' + convert(varchar, datepart(yy, o.orderdate)) as sameyear
,yearendingdate + '/' + convert(varchar, datepart(yy, dateadd(yy,1,o.orderdate))) as plusyear
,yearendingdate + '/' + convert(varchar, datepart(yy, dateadd(yy,-1,o.orderdate))) as minusyear
from @orders o
join @companies c
on o.companyid = c.companyid
select c.companyid
,yearendingdate + '/' + convert(varchar, datepart(yy, dateadd(yy,1,o.orderdate))) as yearending
,sum(ordervalue) as numberoforders
from @orders o
join @companies c
on o.companyid = c.companyid
where orderdate between case when (cast(yearendingdate + '/' + convert(varchar, datepart(yy, o.orderdate)) as datetime) >= o.orderdate)
then yearendingdate + '/' + convert(varchar, datepart(yy, dateadd(yy,-1,o.orderdate)))
else yearendingdate + '/' + convert(varchar, datepart(yy, o.orderdate))
end
and
case when (cast(yearendingdate + '/' + convert(varchar, datepart(yy, o.orderdate)) as datetime) >= o.orderdate)
then yearendingdate + '/' + convert(varchar, datepart(yy, o.orderdate))
else yearendingdate + '/' + convert(varchar, datepart(yy, dateadd(yy,1,o.orderdate)))
end
group by c.companyid, o.orderdate, yearendingdate