Sql server 具有条件的年初至今SQL
我有下表:Sql server 具有条件的年初至今SQL,sql-server,tsql,sql-server-2008-r2,Sql Server,Tsql,Sql Server 2008 R2,我有下表: 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 b
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)
如果我想得到所有值的总和,我只需要跳过分组依据
部分并删除日期部分(月、日)
我有两个参数,分别是
@Month int
和@Year varchar(5)
问题是:我想在所选的
月份
和年份
中添加一些计算例如,如果此简单示例的
@Month参数为,那么下面是您的操作方法。另外,根据您的测试数据,您的值是错误的。一月到三月的总数是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)
declare@table表(oDate日期,[value]int)
插入@table
价值观
('20170101',10),
('20170110',10),
('20170204',20),
('20170301',10),
('20170306',30),
('20170410',40)
声明@Month int=4——将其更改为3、2或1。。。
宣布@Year int=2017
选择
--[月]=日期部分(月,日),
TotalValue=总和(datepart(月,日)时的情况)请提供一些样本数据和样本结果,不清楚您要的是什么。为什么要将四月
乘以2?如果@month>3
为什么还要将@JeffUK完成的月份相加。希望这有助于理解我的问题。@MichałTurczyn,出于某种原因,伙计。:)请阅读一些关于改进您的问题的提示。
TotalValue
-----------
150
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)