年初至今SQL与标准
问题描述:
我有如下表:
年初至今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)
。
现在的问题是:我想在选定的month
和year
中添加一些计算。
例如,如果参数为@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 < = 3和@Year < = '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)
请提供一些样本数据和样本结果,目前尚不清楚您要求的内容。 – JeffUK
为什么乘以'April'2?如果'@month> 3'为什么你总结'月= 3'? –
@JeffUK,完成。希望有助于理解我的问题。 – Haminteu