2014-09-24 62 views
3

我正在尝试编写一个查询,这将允许我只抓取每个月的最新记录,然后对它们进行求和。下面是我的表格的一个例子。我想要做的是选择上个月。如果我能做到这一点,我可以弄清楚如何在2个月前,一年前,本季度等等。只选择每个月的最近记录

下面看,如果我们在10月份,我想抓取和总结只有9个记录/ 24/2014 8:57

我也想要写一个单独的查询,但是做同样的事情,但对于八月。

我的目标是通过声明和设置变量来做到这一点。目前我在每个where子句中使用这个。我只是想搞清楚我需要做的最大(日期)部分。

DECLARE @FirstDayofPrevMonth datetime 
SET @FirstDayofPrevMonth = CONVERT(DATE, DATEADD(MONTH, -1, DATEADD(DAY, 1 - DAY(GETDATE()),  
GETDATE()))) 
DECLARE @LastDayofPrevMonth datetime 
SET @LastDayofPrevMonth = CONVERT(DATE, DATEADD(DAY, 1 - DAY(GETDATE()), GETDATE())) 


DECLARE @FirstDayofPrevMonthPrior datetime 
SET @FirstDayofPrevMonthPrior = dateadd(MONTH, -2,@FirstDayofPrevMonth) 
DECLARE @LastDayofPrevMonthPrior datetime 
SET @LastDayofPrevMonthPrior = DATEADD(MONTH,-2,@LastDayofPrevMonth) 

enter image description here

更新:下面是我用我的最终工作的解决方案:

SELECT SUM(NumofAccounts) AS Total 
       FROM dbo.Summary 
       WHERE ImportDate = (select MAX(importdate) from AllAcctInfoSummary 
        where year(importdate) = year(@LastDayofPrevMonth) 
        and month(importdate) = month(@LastDayofPrevMonth)) 
        group by ImportDate 
+0

您可能希望将测试数据以文本形式包含容易cut'n'paste。 – 2014-09-24 15:28:06

+0

我不知道如何... – donviti 2014-09-24 15:30:52

+0

你是否特别想使用变量?因为有更简单的方法去做 – FuzzyTree 2014-09-24 15:34:54

回答

2

尝试:

select sum(some_column) 
from my_table 
where importdate = 
(select max(importdate) 
from my_table 
where year(importdate) = 2014 
and month(importdate) = 10) 
group by importdate 

可以更换2014年和10在设定年份后有变数和你想要的月份。上面的查询逻辑上是你想要的,你可以修改你使用的变量。您也可以使用FirstDayofPrevMonth变量并调用YEAR和MONTH来获取正确的值以与您的表进行比较。

+0

好的,所以我会被编辑。我再次围绕解决方案跳舞。这工作。我只需要找到一种方法来插入我的变量。虽然如果我能抓住最后一天,我会搜索 – donviti 2014-09-24 15:45:35

+0

@donviti表中的数据,但如果我能抓住最后一天的话,那将非常有帮助。如果您希望当天使用DAY(ImportDate)来获取日期。如果我误解了你想要的,请举个例子。 – Vulcronos 2014-09-24 16:03:29

+0

on month(importdate)= 10我想放入变量'month(importdate)= @FirstDayofPrevMonth' – donviti 2014-09-24 16:11:50

2

这将让你每个月

select ImportDate, sum(NumOfAccounts) 
from mytable t1 
where not exists (
    select 1 
    from mytable t2 where t2.ImportDate > t1.ImportDate 
    and month(t2.ImportDate) = month(t1.ImportDate) 
    and year(t2.ImportDate) = year(t1.ImportDate) 
) 
group by ImportDate 
order by ImportDate 

的每一个最大的可用天的总和,如果你只是想较上月以下内容添加到您那里

and month(dateadd(month,-1,getdate())) = month(ImportDate) 
and year(dateadd(month,-1,getdate())) = year(ImportDate) 

使用同一查询分析功能,应该快一点

select ImportDate, sum(NumOfAccounts) 
from (
    select *, 
    rank() over (partition by month(ImportDate), year(ImportDate) order by ImportDate desc) rk 
    from mytable 
) t1 where rk = 1 
group by ImportDate 
order by ImportDate 
+0

我喜欢这个解决方案好一点。你们在这里很棒。谢谢。最终,就像我说的,我要去上个月。当前季度,在同一个月之前,所以这允许我(我相信)插入我的变量 – donviti 2014-09-24 15:56:38