一年至今的SQL带有标准



我有下表:

oDate        value
------------------------
2017-01-01   10
2017-01-10   10
2017-02-04   20
2017-03-01   10
2017-03-06   30
2017-04-10   40

我想逐月获得所有日期。因此查询应该是:

select datepart(month, oDate) month, SUM(value) TotalValue
from myTable
group by datepart(month, oDate)

如果我想拥有所有值的总数,我只需要跳过group by部分并删除datepart(month, oDate)

我有2个参数,即@Month int@Year varchar(5)
问题是:我想在选定的monthyear中添加一些计算。

例如,如果@Month <= 3@Year <= '2017'的参数为(Jan/2017 TotalValue) + (Feb/2017 TotalValue) + (Mar/2017 TotalValue)

但是,如果@Month > 3@Year = '2017'的参数,则总计为(Jan/2017 TotalValue) + (Feb/2017 TotalValue) + (Mar/2017 TotalValue) + (Apr/2017 TotalValue * 2)

样本结果:
具有第一个条件( @month&lt; = 3和@year&lt; ='2017')

TotalValue
------------
70

使用第二条标准( @month> 3和@year> ='2017')

TotalValue
-----------
150

在第二条标准中,2017年4月的总数为2。所以40 * 2 = 80。从2017年1月到2017年3月的总价值为70,迄今为止第二条标准的一年为70 + 80 = 150

有办法做到吗?
请告知,欢呼。

对于这个简单的样本,这是您的做法。另外,根据您的测试数据,您的价值是错误的。1月 - 3月的总数是80,而不是70。

declare @table table (oDate date, [value] int)
insert into @table
values
('20170101',10),
('20170110',10),
('20170204',20),
('20170301',10),
('20170306',30),
('20170410',40)
declare @Month int = 4       --change this to 3, or 2, or 1...
declare @Year int = 2017
select 
    --[Month] = datepart(month, oDate), 
    TotalValue = SUM(case when datepart(month, oDate) <= 3 then [value] else [value] * 2 end) 
from 
    @table
where
    datepart(year,oDate) = @Year
    and datepart(month, oDate) <= @Month
--group by 
--  datepart(month, oDate)

最新更新