MDX - 如何在维度中考虑开始日期和结束日期按日期汇总

时间:2017-06-28 14:49:39

标签: sql-server ssas mdx

我需要在考虑维度中的开始日期和结束日期的日期范围内计算按日期分组的度量。目标是计算某一特定学校在一段时间内每天活跃的学生人数。

以下SQL代码适用于数据仓库(多维数据集源)。

SELECT 
     t.[date]
    ,count(distinct a.SKStudent) as Students
FROM DM.DimTime t
    CROSS JOIN DM.FactStudents a 
    INNER JOIN DM.DimStudents m ON a.SKStudent = m.SKStudent
    INNER JOIN DM.DimSchool e ON a.SKSchool = e.SKSchool
WHERE t.[date] between '20170502' and '20170512'
    and e.SchoolCode = 123456
    and t.[date] between m.[StartDate] and m.[EndtDate]
GROUP BY t.[data]

结果集如下所示:

+--------------+----------+ 
| date         | Students |
+--------------+----------+ 
| 2017-05-02   |    567   |
| 2017-05-03   |    567   |
| 2017-05-04   |    568   |
| 2017-05-05   |    570   |
| 2017-05-06   |    570   |
| 2017-05-07   |    570   |
| 2017-05-08   |    573   |
| 2017-05-09   |    573   |
| 2017-05-10   |    571   |
| 2017-05-11   |    568   |
| 2017-05-12   |    568   |
+--------------+----------+ 

我尝试制作MDX代码。以下是我的尝试。我不知道如何使用CASE语句中的逻辑(在' ???'标记之间)过滤当天:

WITH SET DateRange AS 
    [Dim Time].[Date].&[20170502]:[Dim Time].[Date].&[20170512]
MEMBER StudentsByDay AS 
    AGGREGATE(DateRange, 
        ???CASE WHEN DateRange.CURRENTMEMBER 
                    BETWEEN [Dim Students].[Start Date] 
                        AND [Dim Students].[End Date] 
                THEN [Measures].[Students Count]
            ELSE NULL END???)
SELECT 
    NON EMPTY { [StudentsByDay] } ON COLUMNS,
    NON EMPTY { [DateRange] } ON ROWS
FROM [Education]
WHERE ( [Dim School].[School Code].&[123456] ) 

1 个答案:

答案 0 :(得分:2)

MDX并不像SQL那样灵活。我建议将以下条件放入FactStudents表中:

t.[date] between m.[StartDate] and m.[EndtDate]

并使用类似的单独措施或替换现有措施。

您需要以下内容:

  1. 具有DateID,StudentID字段的事实表(请参阅下面的代码);
  2. 与学生和日期变暗相关的度量组;
  3. 在StudentID字段上使用DistinctCount聚合的度量。
  4. 事实代码:

    SELECT 
         t.[date] as DateID
        ,a.[SKStudent] as StudentID
    FROM DM.DimTime t
        CROSS JOIN DM.FactStudents a 
        INNER JOIN DM.DimStudents m ON a.SKStudent = m.SKStudent
        INNER JOIN DM.DimSchool e ON a.SKSchool = e.SKSchool
    WHERE e.SchoolCode = 123456
        and t.[date] between m.[StartDate] and m.[EndtDate]