DAX query to calculate distinct count respect to a column after a Filter function - SSAS 2012 Tabular

Hi,
I'm trying to build the dax query to determine the distinct count for a column returned by the application of a Filter function.
evaluate(
row("counter",
countrows(
filter(order_summary,
year(order_summary[change_date]) = 2013) )
I need to count the distinct values for an id returned by the Filter function.
Any helps, please? Thanks

Hi pscorca,
According to your description, you want to calculate the distinct values for records where change_date is 2013. Right?
In this scenario, we can use the DISTINCT() function within COUNTROWS(). Please try the expression below:
=calculate(
countrows(distinct(order_summary[column])),
Filter('order_summary', year(order_summary[change_date])=2013)
Reference:
Distinct Count Measure in PowerPivot using DAX
Related Distinct Count
Best Regards,
Simon Hou
TechNet Community Support

Similar Messages

  • Using HASONEVALUE and SWITCH dax functions - SSAS 2012 Tabular

    Hi,
    I'm testing the behaviour of a series of Dax formulas created in a my tabular model. In order to detect a "strange" anomaly, I'm analyzing in particular this formula:
    IF( HASONEVALUE( Products[ProductID] ),
    SWITCH(
    VALUES( Products[CategoryID] ),
    "Cat1", <measure_for_Cat1>,
    "Cat2", <measure_for_Cat2>,
    For this example, I've a fact table (e.g. having orders) with a product id and a products table with product id, product descr, category id, etc.
    In the pivot table on Excel, product id can be put as a filter or as a row, but the category id (evaluated in the SWITCH function) is not to show to the end user.
    I'd like to understand if a dax formula so built could give an error: when I put the product id as a row the related measure is calculated rightly, but if I try to filter some values for the product id the measure are not determined rightly respect to the
    filtered product id on row. Perhaps, the VALUES in the SWITCH function has a bad behaviour.
    Any suggests to me, please?
    Thanks

    Hi ,
    SUMMARIZE(<table>, <groupBy_columnName>[, <groupBy_columnName>]…[, <name>, <expression>]…)
    SUMMARIZE(ResellerSales_USD
    , DateTime[CalendarYear]
    , ProductCategory[ProductCategoryName]
    , "Sales Amount (USD)", SUM(ResellerSales_USD[SalesAmount_USD])
    , "Discount Amount (USD)", SUM(ResellerSales_USD[DiscountAmount])
    so in cube you for calculated column it would be
    =SUMMARIZE(ResellerSales_USD
    , DateTime[CalendarYear]
    , ProductCategory[ProductCategoryName]
    , "Sales Amount (USD)", SUM(ResellerSales_USD[SalesAmount_USD])
    , "Discount Amount (USD)", SUM(ResellerSales_USD[DiscountAmount])
    thanks
    Please Mark This As Answer or vote for Helpful Post if this helps you to solve your question/problem. http://techequation.com

  • SSAS 2012 Tabular. Analysis Services Query Log not working

    Hello.
    It is possible to configure Analysis Services Query Log on SSAS 2012 Tabular (11.0.3321) server? Or this feature works only with Multidimensional server mode?
    It is not a problem for me to configure Query Log on Multidimensional server. But when I'm trying to do this in Tabular server result is always the same: table S_OlapQueryLog created but no data there.
    This problem exist in our production server. And is fully reproduced in test environment. This problem was reproduced with SQL 2012 RTM, CU4, SP1 and SP1 CU1.
    I tryed to configure Analysis Services Query Log by using SQL account. Later by using windows authentification. Accounts was db owners. Later I have used accounts with sysadmin rights. Results was the same.
    In msmdsrv.log i can find only related events like this:
    (12/7/2012 9:22:59 PM) Message: The query log was started. (Source:
    \\?\P:\Olap\Log\msmdsrv.log, Type: 1, Category: 289, Event ID: 0x41210003)
    (12/7/2012 9:25:03 PM) Message: The query log was stopped. (Source:
    \\?\P:\Olap\Log\msmdsrv.log, Type: 1, Category: 289, Event ID: 0x41210004)
    I'm stuck completely with this functionality. So if someone was much luckier than I please write to me.
    Regards
    Audrius

    I agree with Gerhard's comments, but there are a couple of additional points
    - I am not 100 percent sure if queries that are answered by the SE cache are recorded in the query log
    Queries answered by the SE cache are not definitely not recorded in the QueryLog. So depending on the types of queries and the design of your cube you could possible miss a large proportion of the actual end user queries.
    The QueryLog records the QuerySubcube events and there are zero to many of these generated for a given end user query (zero if the query can be answered from cache). The optimizer may also choose to pre-fetch a wider range of data or to break a single range
    into a few smaller requests so it is not a true indication of the actual query that the end user generated.
    Doing a trace is the only way to catch the actual queries submitted by end users.
    http://darren.gosbell.com - please mark correct answers

  • Sql query to get distinct count

    Hi
    I use SQL Server Management Studio
    can I have a sql query to get count as shown below against  each month column and name column to get distinct count.
    for example if there is two rows with the same date period and same name then the count should be one in first row and zero in the next row of the same data.
    Table Name: Table1
    Column: Month, Name
    Month
    Name
    Count
    12/1/2012 0:00
    AK
    1
    12/1/2012 0:00
    AK
    0
    12/1/2012 0:00
    AB
    1
    1/1/2013 0:00
    AK
    1
    1/1/2013 0:00
    AK
    0
    1/1/2013 0:00
    AB
    1
    3/1/2013 0:00
    AA
    1
    3/1/2013 0:00
    AK
    1
    3/1/2013 0:00
    AK
    0
    6/1/2013 0:00
    AA
    1
    6/1/2013 0:00
    AK
    1
    6/1/2013 0:00
    AK
    0
    9/1/2013 0:00
    AA
    1
    9/1/2013 0:00
    AK
    1
    9/13/2013 0:00
    AK
    1
    10/1/2013 0:00
    AA
    1
    10/1/2013 0:00
    AK
    1
    10/1/2013 0:00
    AK
    0

    Hi,
    Thanks for the query but this query gives the total count like shown below
    if see the second row in the below table AK for 2012-12-1 gives total count as 2 but need the query to show the first row as 1 and there after 0
    query result
    Month name cnt
    2012-12-01 00:00:00.000 AB 1
    2012-12-01 00:00:00.000 AK 2
    2012-12-01 00:00:00.000 AK 2
    2013-01-01 00:00:00.000 AB 1
    2013-01-01 00:00:00.000 AK 2
    2013-01-01 00:00:00.000 AK 2
    2013-03-01 00:00:00.000 AA 1
    2013-03-01 00:00:00.000 AK 2
    2013-03-01 00:00:00.000 AK 2
    2013-06-01 00:00:00.000 AA 1
    2013-06-01 00:00:00.000 AK 2
    2013-06-01 00:00:00.000 AK 2
    2013-09-01 00:00:00.000 AA 1
    2013-09-01 00:00:00.000 AK 1
    2013-09-13 00:00:00.000 AK 1
    2013-10-01 00:00:00.000 AA 1
    2013-10-01 00:00:00.000 AK 2
    2013-10-01 00:00:00.000 AK 2

  • Getting DISTINCT count from two different columns

    Hi all,
    I have following query which gives currency code from two different tables. I would like to get the distinct count of currency codes from these two different columns.
    SELECT eb.person_seq_id, eb.bonus_amount, eb.currency_cd, ed.currency_cd_host
    FROM fr_emp_bonuses eb, fr_emp_details ed, fr_periods p
    WHERE eb.person_seq_id = ed.person_seq_id AND ed.period_seq_id = eb.period_seq_id
    AND ed.period_seq_id = p.period_seq_id AND p.period_status = 'CURRENT'
    AND eb.bonus_amount >= 0 AND eb.person_seq_id = 3525125;
    This query gives following result
    3525125     240000     USD     INR
    3525125     0      USD     INR
    3525125     60000      USD     INR
    3525125     50000      USD     INR
    There are two distinct currency codes (USD, INR) and total amount is 350000. So I am looking for a query to give me the following result
    3525125     350000 2
    Thanks in advance

    Hi,
    Here's one way:
    WITH     original_query     AS
         SELECT  eb.person_seq_id
         ,     eb.bonus_amount
         ,     eb.currency_cd
         ,     ed.currency_cd_host
         FROM     fr_emp_bonuses         eb
         ,     fr_emp_details          ed
         ,     fr_periods          p
         WHERE      eb.person_seq_id    = ed.person_seq_id
         AND      ed.period_seq_id    = eb.period_seq_id
         AND      ed.period_seq_id    = p.period_seq_id
         AND      p.period_status         = 'CURRENT'
         AND      eb.bonus_amount     >= 0
         AND     eb.person_seq_id    = 3525125
    ,     unpivoted_data     AS
         SELECT     person_seq_id
         ,     bonus_amount
         ,     currency_cd
         FROM     original_query
        UNION ALL
            SELECT  person_seq_id
         ,     0               AS bonus_amount
         ,     currency_cd_host     AS currency_cd
         FROM     original_query
    SELECT       person_seq_id
    ,       SUM (bonus_amount)          AS total_bonus_amount
    ,       COUNT (DISTINCT currency_cd)     AS distinct_currency_cds
    FROM       unpivoted_data
    GROUP BY  person_seq_id
    ;There may be a shorter, more efficient way to get the same results, but without knowing more about your tables, I can't tell.
    The tricky thing is getting two columns (currency_cd and currencuy_cd_host in this case) counted together. You can't simply say
    COUNT (DISTINCT eb.currency_cd) +
    COUNT (DISTINCT ed.currency_code_host)That happens to get the correct result with the sample data you posted, but what if you had data like thEe following?
    currency_cd     currency_cd_host
    INR          USD
    USD          INRHere, the count of distinct currency_cds is 2, and the count of distinct currency_cd_hsots is also 2. Does that mean the grand total is 2 + 2 = 4? No, the 2 codes in one column arte the same 2 codes as in the other column. We need to get both currency_cd and currency_cd_hsot into the same column, and then do COUNT (DISTINCT ...) on that combined column. A UNION, as shown above, will certainly do that, starting with your query as you posted it. The query you posted isn't necessarily the best frist step towards this result, however, so there may be a much better approach, depending on your tables.
    Edited by: Frank Kulash on Feb 1, 2012 6:21 PM
    Here's a slightly shorter, and probably more efficient way to get the same results:
    WITH     cntr     AS
         SELECT     LEVEL     AS n
         FROM     dual
         CONNECT BY     LEVEL     <= 2
    SELECT       eb.person_seq_id
    ,       SUM (eb.bonus_amount)          AS total-amount
    ,       COUNT ( DISTINCT CASE
                        WHEN  c.n = 1
                        THEN  eb.currency_cd
                        ELSE  ed.currency_cd_host
                      END
              )               AS distinct_currency_cds
    FROM       fr_emp_bonuses    eb
    ,       fr_emp_details    ed
    ,       fr_periods          p
    ,       cntr              c
    WHERE        eb.person_seq_id  = ed.person_seq_id
    AND        ed.period_seq_id  = eb.period_seq_id
    AND        ed.period_seq_id  = p.period_seq_id
    AND        p.period_status   = 'CURRENT'
    AND        eb.bonus_amount   >= 0
    AND       eb.person_seq_i   = 3525125
    --       NOTE: no join condition involving c; we really do want a cross-join
    GROUP BY  eb.person_seq_id
    ;

  • Distinct count of GRN's in Query PLD

    hi all,
    We have developed a daily grn report and designed report
    using  Query PLD.
    Report contains
    (grn no,date,vendor name,vendor ref no,item code,item
    description,quanity & line total)
    We want to display no of grn's(distinct count)
    @ repetitive area footer.
    Is there any function available in formula field to display
    distinct count of no. of grn's ? / It should done thru query.
    Thanks,
    with regards,
    A.Jeyakanthan

    it will be hard from PLD, instead u can have ur query like,
    SELECT 'Details', '   ',T0.Docnum, T0.CardName, .... FROM OPDN T0 WHERE Month( T0.DocDate ) = Month ('{%0]')
    Union
    SELECT 'Counts', count(T0.DocNum) as 'Doc(s) No', ' ', ' ', ... FROM OPDN T0 WHERE Month( T0.DocDate ) = Month ('{%0]')
    (Replace { with [ )
    Note ' ' is a gap in order to fill the other fields. in first query have given tht '  ' gap purposely so tht the display will not affect ur designing part
    union is used b'coz Count() fn is like aggregate, so wont allow further individual fields coming along with it.
    the 2nd query will occupy only one row, which by grouping u can separate and can hide from repetitive and take the value via formula field by writing that field's id to it into Footer Area.
    Regards,
    Dhana.
    Edited by: Dhanalakshmi C on Mar 5, 2008 1:31 PM

  • Distinct Count doesn't return the expected results

    Hi All,
    I was fighting a little trying to implement a Distinct Count measure over an account dimension in my cube. I read a couple of posts relateed to that and I followed the steps posted by the experts.
    I could process the cube but the results I'm getting are not correct. The cube is returning a higher value compared to the correct one calculated directly from the fact table.
    Here are the details:
    Query of my fact table:
    select distinct cxd_account_id,
              contactable_email_flag,
              case when recency_date>current_date-365 then '0-12' else '13-24' end RECENCY_DATE_ROLLUP,
              1 QTY_ACCNT
    from cx_bi_reporting.cxd_contacts
    where cxd_account_id<>-1 and recency_date >current_date-730;
    I have the following dimensions:
         Account (with 3 different hierarchies)
         Contactable Email Flag (Just 3 values, Y, N, Unknown)
         Recency_date (Just dimension members)
    All dimensions are sparse and the cube is a compressed one. I defined "MAXIMUM" as aggregate for Contactable Email flag and Recency date and at the end, SUM over Account.
    I saw that there is a patch to fix an issue when different aggregation rules are implemented in a compressed cube and I asked the DBA folks to apply it. They told me that the patch cannot be applied because we have an advanced version already installed (Patch 11.2.0.1 ).
    These are the details of what we have installed:
          OLAP Analytic Workspace       11.2.0.3.0 VALID
          Oracle OLAP API 11.2.0.3.0 VALID
          OLAP Catalog 11.2.0.3.0 VALID
    Is there any other patch that needs to be applied to fix this issue? Or it's already included in the version we have installed (11.2.0.3.0)?
    Is there something wrong in the definition of my fact table and that's why I'm not getting the right results?
    Any help will be really appreciated!
    Thanks in advance,
    Martín

    Not sure I would have designed the dimensions /cubes as you,  but there is another method you can obtain distinct counts.
    Basically relies on using basic OLAP DML Expression language and can be put in a Calculated Measure, or can create two Calculated measures
    to contain each specific result.  I use this method to calculate distinct counts when I want to calculate averages, etc ...
    IF account_id ne -1 and (recency_date GT today-365) THEN -
    CONVERT(NUMLINES(UNIQUELINES(CHARLIST(Recency_date))) INTEGER)-
    ELSE IF account_id ne -1 and (recency_date GT today-730 and recency_date LE today-365) THEN -  
    CONVERT(NUMLINES(UNIQUELINES(CHARLIST(Recency_date))) INTEGER)-
    ELSE NA
    This exact code may not work in your case, but think you can get the gist of the process involved.
    This assumes the aggregation operators are set to the default (Sum), but may work with how you have them set.
    Regards,
    Michael Cooper

  • Parameter for ORDER BY in DAX query not respected

    I have an SSRS table fed by a parameterized DAX query (utilizing the methods in
    thesearticles). I have all of my parameters working just fine except for those feeding my closing ORDER BY statement (I am offloading the sorting
    to the Tabular for several reasons, including a large tested performance gain over sorting in SSRS). I have defined the ORDER BY as follows:
    ORDER BY @Order1, @Order2, @Order3, @Order4
    I cannot get even the first parameter to work. I can pass arbitrary strings with no impact on the report returned, though if I hard code the ORDER BY in the query, the ordering is respected, so I know this is a problem with the parameter.
    Running a Profiler trace on the server when I fire the SSRS report returns the following as the parameter value for @Order1:
    <Parameter>
    <Name>Order1</Name>
    <Value xsi:type="xsd:string">Dimuser[UserID-Name]</Value>
    This is exactly what I want to replace @Order1, and when I hard code that exact string into my query I get the behavior I want.
    I have played with \ escaping the brackets to no avail.
    Any insight is greatly appreciated.

    I have discovered a workable solution to my own problem.
    The parameter is passed and interpreted as a quoted string, rather than as a field name.
    I altered my query to follow this general format:
    ORDER BY
    SWITCH( TRUE()
    , @Order1 = "User", DimUser[UserID-Name]
    , SWITCH( TRUE()
    , @Order2 = "User", DimUser[UserID-Name]
    In this way I am comparing two quoted strings for equality and providing an unquoted field identifier that Tabular recognizes and can order by.

  • DAX - Querying: How to reinforce a filter in order to calculate a year to date

    Dear community,
    I am pulling my hair off due to an issue I am having with the creation of a DAX query (supposed to feed an SSRS report).
    The topic is P&L related, I need to compute the revenue based on specific cost elements, that same query must return additional columns that represent YTD, Forecast,... etc ( a couple of typical aggregations).
    First of all here is the query I currently simplified to explain my issue:
    EVALUATE
    CALCULATETABLE(
    SUMMARIZE(
    GENERATE(
    VALUES(AccountingPeriod[RealAccountingPeriod]),
    FactFInancialTransaction
    AccountingPeriod[Code],
    CostElement[Code],
    CostElement[Group],
    "Revenue", [Revenue],
    "GroupRevenue",
    CALCULATE(
    [Revenue],
    all(CostElement[Code])
    FILTER(
    VALUES(CostElement[Code]),
    CostElement[Code] = "RSFOR" ||
    CostElement[Code] = "RSTHI" ||
    CostElement[Code] = "RSOTH"
    FILTER(
    VALUES(CostElement[Group]),
    CostElement[Group] = "RGOVE"
    FILTER(
    ALL(AccountingPeriod),
    AccountingPeriod[Code] = 201402
    FILTER(
    VALUES(OperationalUnit[OperationalUnitNumber]),
    VALUES(OperationalUnit[OperationalUnitNumber]) = "052"
    The Revenue is simply a SUM of an amount column in FactFinancialTransactions.
    What I am unable to do is compute GroupRevenue where I simply would like to sum the revenues for the elements. Does anybody have an idea on the calculate statement that will help me achieve this?
     I tried doing something like:
    CALCULATE(
    [Revenue], all(FactFinancialTransactions),
    all(CostElement[Code]), Values(CostElement[Group]), Values(AccountingPeriod[code]) Values(OperationalUnit[OperationalUnitNumber]) )
    This does not work at all, it looks like the VALUES(OperationalUnit[OperationalUnitNumber]) context is not reinforced, the value I get in return is actually the one summing ALL operational units.
    PS: I have to keep the filter on OperationalUnit as is because it will actually be a pathcontains statement that can pass multiple values
    Thanks so much for any help
    Mils.

    I am not entirely sure about your requirements and your data model.
    However, I would start using ADDCOLUMNS instead of SUMMARIZE to add columns to the group you need.
    EVALUATE
    CALCULATETABLE (
        ADDCOLUMNS (
            SUMMARIZE (
                GENERATE (
                    VALUES ( AccountingPeriod[RealAccountingPeriod] ),
                    FactFInancialTransaction
                AccountingPeriod[Code],
                CostElement[Code],
                CostElement[Group]
            "Revenue", [Revenue],
            "GroupRevenue", CALCULATE ( [Revenue], ALL ( CostElement[Code] ) )
        FILTER (
            VALUES ( CostElement[Code] ),
            CostElement[Code] = "RSFOR"
                || CostElement[Code] = "RSTHI"
                || CostElement[Code] = "RSOTH"
        FILTER (
            VALUES ( CostElement[Group] ),
            CostElement[Group] = "RGOVE"
        FILTER (
            ALL ( AccountingPeriod ),
            AccountingPeriod[Code] = 201402
        FILTER (
            VALUES ( OperationalUnit[OperationalUnitNumber] ),
            VALUES ( OperationalUnit[OperationalUnitNumber] ) = "052"
    Marco Russo (Blog,
    Twitter,
    LinkedIn) - sqlbi.com:
    Articles, Videos,
    Tools, Consultancy,
    Training
    Format with DAX Formatter and design with
    DAX Patterns. Learn
    Power Pivot and SSAS Tabular.

  • What will be the peoplesoft query to calculate voluntary termination count and involuntary termination count? I am working on OBIA HR analytics workforce deployment reports and need to validate the reports

    what will be the peoplesoft query to calculate voluntary termination count and involuntary termination count? I am working on OBIA HR analytics workforce deployment reports and need to validate the reports. I also want to know the tables involved

    Hi Andrew,
    Part A:
    I've done some restating of the question, and distributed the calculations among several fields, not all of which need to be included on the visible layout. Other than formatting the Date fields and moving the 'Completed Date' field and its label, I've left this in the default "Layout 1" produced by AppleWorks.
    Field List:
    Priority: Popup menu with six items: 00, J, D, 1, 2, 3  Defaults to 00
    TL (time limit in months): Calculation:  CHOOSE('Priority',0,1,3,4,6,12)
    Received: Date. Option: Automatically insert today's date (ie. Date Record created) (may be edited)
    Target Date: Calculation:
    DATE(YEAR('Received')+INT(MONTH('Received')+'TL')/12,MOD(MONTH('Received')+'TL', 12),DAY('Received'))
    Remaining (Days): Calculation: INT('Target Date'+1-NOW())  (see revision below)
    Completed: Checkbox. Set default value to Unchecked.
    Completed Date: Date: Entered manually
    OnTarget: Calculation: IF('Completed',IF('Completed Date'<'Target Date',"On Target","Over"),IF(INT(NOW())>'Target Date',"Over","On Target"))
    The On Target field shows the current status of the case while still open, and the state on the closing date when it was closed.
    Having done that, I was unhappy with the Remaining field continuing to calculate an ever larger negative number after the case had been closed. Hence this revision below:
    Remaining: Calculation: IF('Completed','Target Date'-'Completed Date',INT('Target Date'+1-NOW()))
    Shows the number of days remaining while the case is open, the days remaining at completion if the case has been marked Completed and the completion date entered.
    Rsults (and some further formatting of the Layout) below.
    Part B:
    You will need Subsummary parts when sorted on Completed and on On Target. Fields can appear on  a Layout only once, so each subsummary part will need a separate Summary type field for each field to be summarized.
    Regards,
    Barry

  • Running Total & Distinct Count Query

    Crystal 10.0.0.533 CR Professional
    Hope you can assist.
    I have a report listing deals signed, each deal has a corresponding category i.e. industry type, Accountant, Chiropractor, Financial Services, etc.
    I am undertaking a Distinct Count on these categories so that in the group footer it is showing number of different categories signed in a period (the report is grouped into different date periods). This is working OK.
    However, I need to EXCLUDE the category from this distinct count if the deal value is zero.
    I have tried using a formula to show a blank field if the value is zero, however it appears to be distinctly counting the blank as a category?
    Any assistance would be much appreciated.
    Tracy

    Deffinetly it will be less than what you expect for grand total. It is because when you are calculating distinct count for each group suppose
    Group A has categories A,B,C,D-->distinct count (4)
    Group B has C,D,E,F-->distinct count (4)
    but while calculating grand total then the distinct count will be
    A,B,C,D,E,F --> grand total (6) but not (8).
    In this case you need to use mannual running total like this
    whileprintingrecords;
    numbervar i;
    i:=i+{running total};
    place this in group footer and create another fomula like this
    whileprintingrecords;
    numbervar i;
    place this in report footer to get the correct grand total.
    Regards,
    Raghavendra

  • Distinct count inside a measure group with other measures

    Hello,
    I have 1 distinct count inside a measure group with other measures, sum, count etc. I know this is not recommended due to poor processing performance and query response time.
    Processing performance I can live with if it means not having another measure group, which increases processing time anyway.
    I have used the recommended approach before and it generated many questions about what this second measure group is for (visible via excel), even though I made the distinct count appear in the main measure group via a calculated measure.
    (it would be nice if you could hide measure groups)
    However my question is: is query response time only effected when the distinct count is used in the query? Or is query response time effected regardless if the distinct count is used or not??
    Below is an extract from the 2005 distinct count optimizer white paper. It’s not completely clear but I assume if effects queries regardless if distinct count is used or not?
    "By adding other measures to the measure group holding a distinct count measure, all of the other measures will be at the same granularity as the distinct count measure, resulting in inefficient data structures and suboptimal
    queries."

    You might also be interested in reading this blog post, which deals with a similar scenario, to get a feeling for some of the things that might be going on behind the scenes:
    http://cwebbbi.wordpress.com/2012/11/27/storage-engine-caching-measures-and-measure-groups/
    Chris
    Check out my MS BI blog I also do
    SSAS, PowerPivot, MDX and DAX consultancy
    and run public SQL Server and BI training courses in the UK

  • Distinct Count Calculation

    Hello everybody,
    I have a cube with appointments including dimensions for companies and dates.
    One of my measures is "Appointments" which is the count of all appointments. Another calculated member is "Visits" which is the count of appointments with the type of "Visits".
    This is my MDX epxression for "Visits":
    AGGREGATE([Appointment].[Type].&[Visit], [Measures].[Appointments])
    Now I would like to create a new calculated member "Company Visits" which should be the distinct count of "Visits" by company and date.
    Example: 2 "Visits" in one company on the same day should be 1 "Company Visit"
    In T-SQL this query works:
    COUNT(
    DISTINCT(
    CASE [Type]
    WHEN "Visit" THEN CAST([CompanyID] AS NVARCHAR) + CONVERT(NCHAR(8), CAST([Date] AS NVARCHAR))
    ELSE NULL
    END
    ) AS [Company Visits]
    How can I do this with MDX in calculations?
    Additionally I would like to have a calculated member "Days in Field" as distinct count of dates with "Visits".
    Thanks in advance and best regards
    Lars

    Hi Lars,
    Based on your description, you want to create a new calculated member to calculate the distinct count of "Visit" for each company, right? In this case, you can use DistinctCount to achieve your requirement, here is a sample query about DistinctCount function
    for your reqerence.
    with member [DistCount] as
    distinctcount(exists(Employee.Employee.children,,"Reseller Orders"))
    Select {[Measures].[Reseller Order Count],
    [Measures].[DistCount]} on 0,
    ([Employee].[Gender].children) on 1
    From [AdventureWorks]
    Reference:DistinctCount (MDX)
    Regards,
    Charlie Liao
    TechNet Community Support

  • Distinct Count SSAS

    Hi,
    I’m facing a little issue to calculate a distinct count of number of clients in SSAS OLAP Cube. The difficulty appears for the credited client’s accounts, in other words, for the clients how have credit (quantity = -1) or for the clients
    how have bought the product and they receive a credit after (quantity = 0). My actual distinct count in my cube considers these two cases as real buying transaction, but in fact they’re not.  I’ve checked in SSAS to make a distinct count with the expression
    (SUM Quantity > 1), but I didn’t find nothing. Now I’m thinking to model these cases directly in my Datawarehouse, but I don’t see how can’t do it.  Can anyone de give me a little help? Thanks.

    Hi Merouane,
    According to your description, you want to count the members with the condition quantity=-1, right? In this case, we can use Filter function inside the Count function. The query will looks like below.
    Count(Filter([Product].[Product].[Product], [Measures].[Internet Order Quantity] =-1))
    However, the Filter function might cause a performance issue, we can change the query to
    Sum(
       [Product].[Product].[Product],
       Iif([Measures].[Internet Order Quantity] =-1,1,0))
    For the detail information about it, please refer to the link below.
    http://sqlblog.com/blogs/mosha/archive/2007/11/22/optimizing-count-filter-expressions-in-mdx.aspx
    Regards,
    Charlie Liao
    TechNet Community Support

  • Distinct count mdx fails

    Hi,
    I have a question about performing a distinct count of number of clients in my cube OLAP. 
    My clients-dimension table is populated from 4 different databases, this means that I can find the same clients with different Clients_ID (Natural key), because each client has a different ID in every database.  
    I want to calculate a distinct count on client’s phone number because it’s the same record in all Databases, I always get a big number which is not the right result.  I checked deeply the issue and I found that the query I set seems
    to not perform the distinct count right on the phone number.
    The small test I did with only filters (see screenshot below) let me believe that my query is performing the distinct count on each client ID instead of the phone number.
    Here it is the query I used to perform my distinct count:
    WITH SET MySet AS
    Filter(
    {[Dim Date].[Year].&[2014]} *
    {[DIM FA Clients].[FaCuNumberX].[FaCuNumberX]},[Measures].[QQT - Fact Ventes]>1 or [Measures].[QQT - Fact Ventes]=1)
    MEMBER MEASURES.SETDISTINCTCOUNT AS
    DISTINCTCOUNT(MySet)
    SELECT {MEASURES.SETDISTINCTCOUNT} ON 0
    FROM [CubeAll]
    I don’t know why the filter on this mdx query doesn’t work properly like an SQL group by.
    Thanks for help! 

    Hi Merouane,
    According to your description, you want to calculated to the numbers of client by count distinct Phone Number, right?
    In your scenario, you can add a distinct count measure in your project. Distinctcounts are one of the most demanding requests that can be placed on a MOLAP database, caused by the large number of dimensional attributes that typically exist in a cube. Here
    is a blog which describe several solutions for distinctcount in a SSAS project, please refer to the link below to see the detais.
    http://www.mssqltips.com/sqlservertip/3043/different-options-for-creating-a-distinct-count-measure-in-ssas/
    Regards,
    Charlie Liao
    TechNet Community Support

Maybe you are looking for

  • Delete Workflow items from workflow inbox.

    Hello All, We are using workflow in MSS for Compensation Management. As part of this an email will be sent to the managers when a compensation needs an approval. There are some workflow items under workflow inbox ( SBWP ) . How can I delete emails wh

  • How to save my query made by Query Builder ? is it possible

    Do you know how to do it ?

  • Sharing item/folder in SharePoint 2013 on-prem

    I'm trying to share an item/folder in a library (in a subsite that has unique permissions) to a user that doesn't have access to the site/library. Is this even possible? I've tried to share the item/folder directly with read permissions, but that doe

  • BI_PROCESS_TRIGGER event job in released status ONLY

    HI ALL, I WANT TO TRIGGAR PC TWICE IN DAY 5 PM AND 2AM. 1.I CTEATED EVENT IN SM62 (ZSDPC_EVENT) 2.I CTEATED SE 38 PROGRAM (zsdpp_pc_event_program )LIKE BELOW REPORT  zsdpp_pc_event_program. DATA: gv_time TYPE sy-uzeit,       eventid TYPE btceventid.

  • Album not opens in gallery

    my photo album wont opens in gallery it shows only blck screen while it opens in file manager!!plz help me!!