2014-04-18 52 views
0

所以我有這個代碼,這是爲了抓取最近11個月的銷售數據,包括當前月份,使它成爲一整年。我需要做些什麼才能將其轉變爲抓取過去12個月和當前月份的數據?我知道我必須改變右邊的東西(選擇期間)...但不知道如何抓取過去13個月的數據?

在這一個,左邊的函數顯示如何獲得當前年份(2014)減1給予2013年,但我不明白正確的功能,2是什麼意思? 謝謝

period <= (
    SELECT Period 
    FROM dbo.FiscalDates 
    WHERE (Date = CONVERT(varchar(10), GETDATE(), 102))) and period >= (
convert(varchar, left((
    SELECT Period 
    FROM dbo.FiscalDates 
    WHERE (Date = CONVERT(varchar(10), GETDATE(), 102))),4)-1)+'-'+ 
convert(varchar, right((
    SELECT Period 
    FROM dbo.FiscalDates 
    WHERE (Date = CONVERT(varchar(10), GETDATE(), 102))),2))) 
group by prodnum, period, WhseNum 
+1

哇你爲什麼要轉換的日期'VARCHAR' ??? – Zane

+0

WHERE YourColumn> = DATEADD(MONTH,-13,CAST(GETDATE()AS DATE))' – Zane

+0

@Zane,我始終使用該轉換將日期轉換爲更易讀的形式,可以導出(在此情況下,'yyyy.mm.dd')。有關各種轉換,請參閱http://www.sql-server-helper.com/tips/date-formats.aspx。但是,我仍然不確定他爲什麼在Where子句中使用它。 – PowerUser

回答

10

哇哦夥計我想你可能會在這裏過於複雜。如果你想獲得過去X個月的數據,那麼只需使用DATEADD這是一個非常的useful function

所有你需要做的就是

select 
    YourColumns 
FROM YourTable 
WHERE YourDate >= DATEADD(MONTH, -13, CAST(GETDATE() AS DATE)) 

然後咣噹你去那裏。

0
 DECLARE 
     @FormYear AS INT, 
     @FormMonth AS INT, 
     @ToYear AS INT, 
     @ToMonth AS INT, 
     @FromDate AS DATE, 
     @ToDate AS DATE 

     SET @FormYear=YEAR(DATEADD(DAY, -365, GETDATE())) 
     SET @FormMonth=MONTH(DATEADD(DAY, -365, GETDATE())) 

     SET @ToYear=YEAR(GETDATE()) 
     SET @ToMonth=MONTH(GETDATE()) 

     SET @FromDate= CAST(CAST(@FormMonth AS VARCHAR) +'-'+'01'+ '-' +CAST(@FormYear AS VARCHAR) AS DATE) 
     SET @ToDate= CAST(CAST(@ToMonth AS VARCHAR) +'-' + '01'+'-' + CAST(@ToYear AS VARCHAR) AS DATE) 

之後,只需選擇 -

YourDateField Between @FormDate AND @ToDate 
相關問題