PowerBI 时间切片器默认选择最新日期

之前有看到别人实现的,是这样的格式: (传送门:https://blog.csdn.net/qq844385029/article/details/94587030)
PowerBI 时间切片器默认选择最新日期_第1张图片

如果是年、月、日分开的,又应该怎么设置呢?

有2种办法
(1)导入模式

可通过DAX函数解决,新建计算列,分别将【年度】、【月份】、【日】转换为本年、本月、本日, 然后切片器选择分别选择本年、本月、本日

本年 =
IF ( [年度] = YEAR ( TODAY () ), "本年 ", FORMAT ( [年度], "" ) )

本月=
IF ( [月份索引] = MONTH ( TODAY () ), "本月", FORMAT ( [月份], "" ) )

本日 =
IF ( [] = DAY ( TODAY () ), "本日", FORMAT ( [], "" ) )

(2)DirectQuery模式
直接查询模式下没办法新建数据列,需要在数据库新建日历表

CREATE TABLE [dbo].[Calendar] ( 
   [time_id] [int] IDENTITY (1, 1) NOT NULL primary key, 
   [the_date] [datetime] NULL , 
   [the_day] [nvarchar] (15) NULL , 
   [the_month] [nvarchar] (15) NULL , 
   [the_year] [smallint] NULL , 
   [day_of_month] [smallint] NULL , 
   [week_of_year] [smallint] NULL , 
   [month_of_year] [smallint] NULL , 
   [quarter] [nvarchar] (2) NULL , 
   [fiscal_period] [nvarchar] (20) NULL 
)
 
DECLARE @WeekString varchar(12), 
@dDate SMALLDATETIME, 
@sMonth varchar(20), 
@iYear smallint, 
@iDayOfMonth smallint, 
@iWeekOfYear smallint, 
@iMonthOfYear smallint, 
@sQuarter varchar(2), 
@sSQL varchar(100), 
@adddays int 
   
SELECT @adddays = 1 --日期增量(可以自由设定) 
SELECT @dDate = '01/01/2019' --开始日期,根据需要调整 
   
WHILE @dDate < '12/31/2022'  --结束日期 ,根据需要调整 
BEGIN 
   
   SELECT @WeekString = DATENAME (dw, @dDate) 
   SELECT @sMonth=DATENAME(mm,@dDate) 
   SELECT @iYear= DATENAME (yy, @dDate) 
   SELECT @iDayOfMonth=DATENAME (dd, @dDate) 
   SELECT @iWeekOfYear= DATENAME (week, @dDate) 
   SELECT @iMonthOfYear=DATEPART(month, @dDate) 
   SELECT @sQuarter = 'Q' +  CAST(DATENAME (quarter, @dDate)as varchar(1))
   INSERT INTO Calendar(the_date, the_day, the_month, the_year, 
   day_of_month, 
   week_of_year, month_of_year, quarter) VALUES 
   (@dDate, @WeekString, @sMonth, @iYear, @iDayOfMonth, @iWeekOfYear, 
   @iMonthOfYear, @sQuarter) 
   SELECT @dDate = @dDate + @adddays 
END 
GO 

然后建立视图:

CREATE VIEW [dbo].[VCalendar] AS SELECT 
  [the_date],
	CASE WHEN CONVERT(VARCHAR(4),the_date,120) = CONVERT(VARCHAR(4),GETDATE(),120) THEN '本年'
			 ELSE CONVERT(VARCHAR(4),the_date,120) END AS CurrentYear,
			 
	CASE WHEN CONVERT(VARCHAR(2),the_date,101) = CONVERT(VARCHAR(2),GETDATE(),101) THEN '本月'
		 ELSE CONVERT(VARCHAR(2),the_date,101) END AS CurrentMonth,
		 
	CASE WHEN CONVERT(VARCHAR(2),the_date,103) = CONVERT(VARCHAR(2),GETDATE(),103) THEN '本日'
	 ELSE CONVERT(VARCHAR(2),the_date,103) END AS CurrentDay
FROM Calendar

就可以提取到本年、本月、本日了

通过【the_date】字段与其他表的日期相连接(截图我的的字段名是改了的,the_date名称可根据需要进行修改)
PowerBI 时间切片器默认选择最新日期_第2张图片
最后切片器直接在年、月、日对应的地方放入【本年】、【本月】、【本日】即可。
在这里插入图片描述

你可能感兴趣的:(避坑,sql,bi,sqlserver)