计算预算总和

时间:2015-11-02 09:20:32

标签: sql sql-server-2008

我有这样的表预算:

╔════╦══════╦═══════╦═══════════╦══════╗
║ Id ║ Site ║ Rayon ║   Date    ║ Amt  ║
╠════╬══════╬═══════╬═══════════╬══════╣
║  1 ║   20 ║    23 ║ 2015-11-3 ║  200 ║
║  2 ║   40 ║     2 ║ 2015-12-4 ║   20 ║
║  3 ║   20 ║     3 ║ 2015-11-4 ║  400 ║
║  4 ║   30 ║    13 ║ 2015-11-5 ║  500 ║
║  5 ║   20 ║    23 ║ 2015-08-3 ║  200 ║
╚════╩══════╩═══════╩═══════════╩══════╝

如何计算从今天到月底以及从今天到年底的amt总和?

3 个答案:

答案 0 :(得分:2)

对于这样的问题,你需要做的第一件事就是明白如何计算"本月底"和"今年年底"。使用sql2008,您无权访问有用的函数EOMONTH(),因此您必须自己计算。

a few different ways of doing this但是我已经去了一个会计算当月最后一天午夜和当年最后一天的几个毫秒的人。

declare @date DATETIME = getdate()

select dateadd(millisecond,-3,DATEADD(MONTH,datediff(MONTH,0,@date)+1,0)) as EOMONTH
select dateadd(millisecond,-3,DATEADD(year,datediff(year,0,@date)+1,0)) as EOYEAR

(注意:-3是由于sql server的dattime数据类型为minimum accuracy of 3ms所以从下个月/下一个开始需要3毫秒年份和你一样准确无误。无论如何,重要的是我们所要做的就是尽可能接近月末/年末的日期边界)

鉴于此位已经解决,您可以在2个不同的查询中单独使用它们

DECLARE @now DATETIME = GETDATE();
DECLARE @eomonth DATETIME = dateadd(millisecond,-3,DATEADD(MONTH,datediff(MONTH,0,@date)+1,0))
DECLARE @eoyear DATETIME = dateadd(millisecond,-3,DATEADD(year,datediff(year,0,@date)+1,0)) 

SELECT SUM(amt) FROM Budget
WHERE date >= @now AND date <=@eomonth

SELECT SUM(amt) FROM Budget
WHERE date >= @now AND date <= @eoyear

或者,你可以将它们结合起来

SELECT SUM(CASE WHEN DATE<@eomonth THEN Amt ELSE 0 END) AS summonth,
      SUM(CASE WHEN DATE<@eoyear THEN Amt ELSE 0 END) AS sumyear
FROM Budget 
WHERE Date>=@date

答案 1 :(得分:1)

本月末:

SELECT SUM(Amt) AS Amt 
FROM TableName
WHERE Date >= CAST(GETDATE() AS DATE) AND 
      Date < DATEADD(m, 1, DATEADD(dd, -DAY(GETDATE()) + 1, CAST(GETDATE() AS DATE)))

今年年底:

SELECT SUM(Amt) AS Amt 
FROM TableName
WHERE Date >= CAST(GETDATE() AS DATE) AND 
      Date < CAST(YEAR(GETDATE()) + 1 AS char(4)) + '0101'

答案 2 :(得分:0)

不幸的是,您的sql版本较旧,不支持名为EOMONTH

的系统函数
  

这个简单的函数与 EOMONTH等效。这个函数在复杂的日期计算中非常有用,可以减少查询长度。

CREATE FUNCTION dbo.endofmonth(@date DATETIME= NULL)
RETURNS DATETIME
BEGIN
RETURN DATEADD(DD, -1, DATEADD(MM, +1, DATEADD(DD, 1 - DATEPART(DD, ISNULL(@date,GETDATE())), ISNULL(@date,GETDATE()))))
END

执行查询:

SELECT dbo.endofmonth(DEFAULT)  --Current month-end date
SELECT dbo.endofmonth('02/25/2012') --User-defined month-end date

您的情况

/**** To get end of current month ****/

SELECT SUM([amt]) FROM budget WHERE [date] >= getdate() AND [date] <= CONVERT(DATE,dbo.endofmonth(DEFAULT))

/**** To get end of current year  ****/
SELECT SUM([amt]) FROM budget WHERE [date] >= getdate() AND [date] <= CONVERT(DATE,DATEADD(yy, DATEDIFF(yy,0,getdate()) + 1, -1))