【问题标题】:Get the amount of days in a month - mdx获取一个月的天数 - mdx
【发布时间】:2015-06-09 23:56:33
【问题描述】:

在 TSQL 中,我可以这样做来获取某个月的天数:

declare @date as datetime
set @date = '2015-02-06'
select datediff(day, dateadd(day, 1-day(@date), @date),
              dateadd(month, 1, dateadd(day, 1-day(@date), @date))) 

如何在 MDX 中获得相同的功能? 附:我需要结果是一个 int。

【问题讨论】:

  • 创建日期维度。
  • 我有一个,但里面没有一个月的天数。
  • @PaulKar。它只是您维度中的一个额外列,它使用您已有的 sql。然后,这可能是多维数据集中每个日期的属性 - 比所提供的 mdx 解决方案更简单、更有效。

标签: sql-server tsql mdx cube


【解决方案1】:

如果您有一个年-月-日层次结构,可以按以下方式完成:

WITH MEMBER NumOfDaysInMonth AS
DateDiff(       
            "d",
             HEAD(DESCENDANTS([Date].[Calendar Date].CURRENTMEMBER, 1)).ITEM(0).MEMBER_CAPTION, //Gets the first date of the month
             TAIL(DESCENDANTS([Date].[Calendar Date].CURRENTMEMBER, 1)).ITEM(0).MEMBER_CAPTION  //Gets the last date of the month
        ) + 1

您只需要在切片器中传递月份的值。计算出的成员将完成剩下的工作。

SELECT NumOfMonths ON 0
FROM [YourCube]
WHERE ([Date].[Calendar Date].[Month].&[Dec-2015])

【讨论】:

  • 一些多维数据集设计者在他们的多维数据集中不包括未来的日期成员。我们的多维数据集目前仅包含截至 6 月 9 日的内容。您的方法在这种情况下不起作用。
  • 我的多维数据集在 DIM.Date 中有未来日期,但我认为添加一列会更简单。如果我不这样做,我会使用这个答案,因为它看起来更简单。
  • 你能解释一下 select 在这里做什么吗?是选择 2015 年 12 月吗?我希望它是动态的,而不是特定月份的。
  • 是的,它正在这样做。如果您希望月份是动态的,则必须使用 StrToSet 函数并在 WHERE 子句中传递参数,而不是 [Date].[Calendar Date].[Month].&[Dec-2015]
  • 如果我想创建一个成员而不是按年/月切片,我该怎么做?
【解决方案2】:

这是我们使用的方法:

WITH 
  MEMBER [MEASURES].[NumOfDaysInMonth] AS 
    IIF
    (
      VBA!Isdate([Date].[Calendar].CurrentMember.Name)
     ,Datepart
      ("D"
       ,
          Dateadd
          ("M"
           ,1
           ,Cdate
            (
                Cstr(VBA!Month([Date].[Calendar].CurrentMember.Name)) + "-01-"
              + 
                Cstr(VBA!Year([Date].[Calendar].CurrentMember.Name))
            )
          )
        - 1
      )
     ,''
    ) 
SELECT 
  NON EMPTY 
    {[MEASURES].[NumOfDaysInMonth]} ON 0
 ,NON EMPTY 
    {
      [Date].[Calendar].[All]
     ,[Date].[Calendar].[Calendar Year].&[2005]
     ,[Date].[Calendar].[Calendar Semester].&[2008]&[2]
     ,[Date].[Calendar].[Month].&[2006]&[3]
     ,[Date].[Calendar].[Date].&[20060214]
     ,[Date].[Calendar].[Month].&[2007]&[11]
    } ON 1
FROM [Adventure Works];

以上返回如下:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-19
    • 1970-01-01
    • 2014-08-15
    • 1970-01-01
    • 1970-01-01
    • 2021-07-30
    相关资源
    最近更新 更多