2017-06-18 113 views
0

我是SQL查詢世界的新手,陷入了一個需求。月份差異沒有額外的表

在我的查詢中,我有toDatefromdate輸入參數,根據業務邏輯它將返回如下結果。

結果: -

Month 
Dec-16 
Dec-16 
Dec-16 
Feb-17 
Feb-17 
Mar-17 
Mar-17 

現在查詢應該需要返回數據每月,如果我們沒有對perticular月的數據(圖像這是揚),那麼它應該插入數據並返回數據那一個月,在圖片上我們可以看到,對於Jan,我們沒有任何數據。

+1

的可能的複製[包括在集團遺漏月通過查詢](https://stackoverflow.com/questions/11479918/包括缺少月份在組中查詢) –

+0

我沒有看到您的文章中的任何圖像,我也注意到一些細節的缺乏。您能詳細瞭解用於從'toDate'和'FromDate'確定月份的業務邏輯嗎? 「存儲特定月份的數據」在哪裏?新數據如何計算? –

回答

1

您可以使用日曆或日期表來處理這類事情。

沒有日曆表,你可以使用common table expression只有這樣生成即席一套月:

declare @fromdate date = '20161201'; 
declare @todate date = '20170301'; 
;with n as (select n from (values(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) t(n)) 
, Months as (
    select top (datediff(month, @fromdate, @todate)+1) 
    [Month]=convert(date,dateadd(month,row_number() over(order by (select 1))-1,@fromdate)) 
    from n as deka cross join n as hecto cross join n as kilo 
    order by [Month] 
) 
/* your query here: */ 
select 
    d.[Month] 
    , sum_col = sum(t.col) 
from Months 
    left join tbl t 
    on d.[Month] = t.[Month] 
group by d.[Month] 

號碼和日曆表參考:

0

解決查詢: -

Declare @customDate DATETIME 
declare @datafound integer 
set @customDate = @fromDate 

    WHILE @customDate < @toDate 
    BEGIN 
     select @datafound = count(1) from @temp where datepart(month, MonthDate) = datepart(month, @customDate) 
     if @datafound = 0 
     select Format(@customDate,'MMM-yy') as Month 

    SET @customDate = DATEADD(month, 1,@customDate) 


END;