在Power BI中根據選定的月份,動態顯示最近N個月的數據


1)出於本文的目的,我使用一個非常簡單的模型-一個Sales表(僅包含Date和Sales)和一個Date表。

圖片

2)創建如下所示的3個度量,然后將這3個度量與一個月切片器一起添加到報告中,如下所示。您可以在切片器中更改月份,並驗證所選月份的度量值是否已更改。

Sales (Selected Month) = SUM ( Sales[Sales] )

Sales Last Year = CALCULATE ( SUM ( Sales[Sales] ), SAMEPERIODLASTYEAR ( ‘Date'[Date] ) )

Sales YTD = TOTALYTD ( SUM ( Sales[Sales] ), ‘Date'[Date] )

 

 

 

3)下一步是制定一個顯示最近N個月的度量。讓我們創建一個稱為N What If參數,其值從1到24,增量為1。將其放置在圖表中,如下所示

圖片


4)此技術的主要步驟是–創建一個度量標准,以顯示最近N個月的銷售總額。重要的是要知道將“日期”表中的“月份”放不下,所以我們要做的是在“銷售”表中創建“月份”列,然后將其用作條形圖的軸。在Sales表中創建2個計算列(MonthYear以及MonthYearNo(用於對MonthYear列進行排序)),以及度量-Sales(最近n個月)。

MonthYear = RELATED ( ‘Date'[MonthofYear] )

MonthYearNo = RELATED ( ‘Date'[MonthYearNo] )

Sales (last n months) =
VAR MaxFactDate =
    CALCULATE ( MAX ( Sales[Date] ), ALL ( ‘Date’ ) ) — ignore the selected date filter, and find the max of date in Sales table
VAR FDate =
    ENDOFMONTH ( ‘Date'[Date] ) — get the last day of the month selected in the date filter
VAR Edate =
    EDATE ( FDate, – [N Value] ) — get the last day of -N months
RETURN
    IF (
MaxFactDate <= MAX ( ‘Date'[Date] )
&& MaxFactDate > Edate,
        CALCULATE ( SUM ( Sales[Sales] ), ALL ( ‘Date’ ) )
    ) — if the date in the fact table is between the last N months, display Sales, else nothing. Note that we are ignoring the date filter, only respect the date in Fact

  

或者

Sales (last n months) =
CALCULATE (
    SUM ( Sales[Sales] ),
    DATESINPERIOD ( ‘Date'[Date], MAX ( ‘Date'[Date] ), – [N Value], MONTH )
)

5)現在,創建一個條形圖,在“軸”上的“年年”和在值上的“銷售額”(最近n個月),如下所示。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM