2014-09-24 60 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