Accumulative Distinct Counts

I’ve been at this for two days now. Could someone lead me down the right path? Given the following data set:
create table data_owner.test_data
item_number varchar2(10 byte),
store_number varchar2(10 byte),
calendar_year varchar2(10 byte),
calendar_week varchar2(10 byte),
units_sold integer
insert into test_data(item_number, store_number, calendar_year, calendar_week, units_sold)
values ('1111', '31', '2010', '51', 4)
insert into test_data(item_number, store_number, calendar_year, calendar_week, units_sold)
values ('1111', '16', '2010', '51', 2)
insert into test_data(item_number, store_number, calendar_year, calendar_week, units_sold)
values ('1111', '31', '2010', '52', 3)
insert into test_data(item_number, store_number, calendar_year, calendar_week, units_sold)
values ('1111', '27', '2010', '52', 1)
insert into test_data(item_number, store_number, calendar_year, calendar_week, units_sold)
values ('1111', '16', '2011', '1', 3)
insert into test_data(item_number, store_number, calendar_year, calendar_week, units_sold)
values ('1111', '27', '2011', '2', 5)
insert into test_data(item_number, store_number, calendar_year, calendar_week, units_sold)
values ('1111', '20', '2011', '2', 4)
insert into test_data(item_number, store_number, calendar_year, calendar_week, units_sold)
values ('2222', '27', '2010', '51', 3)
insert into test_data(item_number, store_number, calendar_year, calendar_week, units_sold)
values ('2222', '16', '2010', '52', 2)
insert into test_data(item_number, store_number, calendar_year, calendar_week, units_sold)
values ('2222', '20', '2010', '52', 1)
insert into test_data(item_number, store_number, calendar_year, calendar_week, units_sold)
values ('2222', '16', '2011', '1', 3)
insert into test_data(item_number, store_number, calendar_year, calendar_week, units_sold)
values ('2222', '31', '2011', '2', 3)
select * from test_data
item_number     store_number     calendar_year     calendar_week     units_sold
1111     31     2010     51     4
1111     16     2010     51     2
1111     31     2010     52     3
1111     27     2010     52     1
1111     16     2011     1     3
1111     27     2011     2     5
1111     20     2011     2     4
2222     27     2010     51     3
2222     16     2010     52     2
2222     20     2010     52     1
2222     16     2011     1     3
2222     31     2011     2     3
My desired result is a sum of units sold and an accumulative distinct count of store numbers grouped by item, year, and week. i.e.:
item_number     calendar_year     calendar_week     store_count     sum(units_sold)
1111     2010     51     2     6
1111     2010     52     3     4
1111     2011     1     3     3
1111     2011     2     4     9
2222     2010     51     1     3
2222     2010     52     3     3
2222     2011     1     3     3
2222     2011     2     4     3
I can’t seem to get the store count right. I’ve been trying various methods of the count(distinct store_number) over (…) analytic function, but nothing works. Thanks.

Hi,
Interesting problem!
When using analytic functions, you can't use both DISTINCT and ORDER BY. Too bad; that sure would be convenient.
The most general solution is to use aggregate functions instead of analytic functions, and do a self-join to pair every row ("table" l, for "later" in the query below) with every earleir row ("table" e below) for the same item:
SELECT       l.item_number
,       l.calendar_year
,       l.calendar_week
,       COUNT (DISTINCT e.store_number)     AS store_count
,       SUM (l.units_sold)
     / COUNT (DISTINCT e.ROWID)          AS total_units_sold
FROM       test_data   e
JOIN       test_data   l      ON     e.item_number     = l.item_number
AND                               e.calendar_year || LPAD (e.calendar_week, 2)
                                <= l.calendar_year || LPAD (l.calendar_week, 2)
GROUP BY  l.item_number
,       l.calendar_year
,       l.calendar_week
ORDER BY  l.item_number
,       l.calendar_year
,       l.calendar_week
;You might think about storing a DATE (say, the date when the week begins) instead of year and week. It would simplify this query, and probably lots of other ones, too. I realize that might complicate some other queries, but I think you'll fiond a net gain.
Thanks for posting the CREATE TABLE and INSERT statements; that helps a lot!
Edited by: Frank Kulash on Nov 18, 2011 12:48 PM
Here's an analytic solution. As you can see, it requires more code, and more complicated code, but it might perform better:
WITH     got_r_num   AS
     SELECT     item_number
     ,     calendar_year
     ,     calendar_week
     ,     units_sold
     ,     ROW_NUMBER () OVER ( PARTITION BY  item_number
                               ,                    store_number
                         ORDER BY        calendar_year
                         ,                calendar_week
                       )      AS r_num
     FROM    test_data
SELECT DISTINCT
     item_number
,     calendar_year
,     calendar_week
,     COUNT ( CASE
                    WHEN  r_num = 1
              THEN  1
                END
           )             OVER ( PARTITION BY  item_number
                                  ORDER BY      calendar_year
                      ,          calendar_week
                             )                    AS store_count
,       SUM (units_sold) OVER ( PARTITION BY  item_number
                                ,             calendar_year
                      ,             calendar_week
                         )                         AS  total_units_sold
FROM       got_r_num
ORDER BY  item_number
,            calendar_year
,       calendar_week
;This approah will not work in all windowing situations. It's okay fo this job, but not if you wanted,for example, a count of distinct stores from the last 6 weeks, and the report covers more than 6 weeks.

Similar Messages

  • [SQL] how can i get this result....??(accumulation distinct count)

    [SQL] how can i get this result....??(accumulation distinct count)
    Hi everybody,
    pls tell me how can it possible to get result?
    ### sample data
    date visitor
    10-01 A
    10-01 A
    10-01 B
    10-01 B
    10-01 C
    10-01 C
    10-02 A
    10-02 C
    10-02 C
    10-02 D
    10-02 D
    10-03 B
    10-03 B
    10-03 B
    10-03 A
    10-03 A
    10-03 F
    10-04 A
    10-04 A
    10-04 F
    result that i want...like this.
    date date_unqiue_visitors acc_date_unique_visitors
    10-01 3 3
    10-02 3 4
    10-03 3 5
    10-04 2 5
    date distinct visitors : count(distinct visitor)
    but how can i get accumulation distinct visitor count???
    Thanks to every body..

    SQL> select dt,cnt,sum(cnt1) over(order by dt) cnt1
      2  from(
      3  select dt,count(distinct visitor) cnt,sum(flg) cnt1
      4  from
      5   (select dt,visitor,(select decode(count(*),0,1,0)
      6                           from test
      7                           where rowid < t.rowid
      8                           and visitor = t.visitor) flg
      9   from test t)
    10  group by dt);
    DT                CNT       CNT1
    10-01               3          3
    10-02               3          4
    10-03               3          5
    10-04               2          5
    Message was edited by:
            jeneesh
    Wrong...                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • 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

  • Report using Tabular Model and Measures based on Distinct Counts

    Hello,
    I am creating a report that should present something like this:
    YEAR-1 | MONTH-1 | MONTH-2 | MONTH-3... | YEAR | MONTH-1 | MONTH-2 | MONTH-3...
    My problem is that when designing the dataset to support this layout I drag the Year, Month and Distinct count Measure, but on the report when I want the value for the YEAR level I don't have it and I cannot sum the months value...
    What is the best aproach to solve this? Do I really have to go to advanced mode and customize my MDX or DAX? Can't basic users do something like this that seems so trivial and needed?
    Thank you
    Luis Simões

    Hi Luis,
    According to your description, you create a Reporting Services report using Analysis Service Tabular Model as the datasource, now what you want is sum the months value on year level, right?
    In your scenario, you can add the Month field to column group, add a parent group using Year Field and then add a Total on Month group. In this case, Reporting Services will sum the months value on Year level. I have tested it on my local environment, the
    screenshot below is for you reference.
    Reference:Lesson 6: Adding Grouping and Totals (Reporting Services)
    If this is not what you want, please describe your dataset structure, so that we can make further analysis.
    Regards,
    Charlie Liao
    TechNet Community Support

  • How to get Distinct Count of Products across two dimensions

    Hi,
    I have two dimensions, Item and Presentations. I need to get distinct count of products for IMD_Id + Merc_Pres_Id. IMD_Id is the lowest member in Item and Merc_Pres_Id is lowest in Presentation. My MDX query is given below but when I apply filters to
    slice it, it does not work and does not give right count. It always gives the count for all.
    /* Last Year Demand - Demand for 12 months back of selected months */
    With
    Member [Measures].[LYDemand]
    as
    Sum(
    Generate(
    EXISTING[All Date].[Fiscal Month Name].[Fiscal Month Name].Members,
    {parallelperiod([All Date].[Fiscal Month Name].[Fiscal Month Name], 12
    ,[All Date].[Fiscal Month Name].CurrentMember)}
    ,[Measures].[Proj Demand]
    /* Last to last Year Demand - Demand for 24 back of selected months */
    Member [Measures].[LLYDemand]
    as
    Sum(
    Generate(
    EXISTING[All Date].[Fiscal Month Name].[Fiscal Month Name].Members,
    {parallelperiod([All Date].[Fiscal Month Name].[Fiscal Month Name], 24
    ,[All Date].[Fiscal Month Name].CurrentMember)}
    ,[Measures].[Proj Demand]
    /* Current Year Active Products */
    Member [Measures].[CYCount]
    as
    CASE
    WHEN
    [Measures].[Proj Demand] > 0
    THEN
    DistinctCount(Existing(([All Items].[IMD Id].[IMD Id],[All Merchandise Presentations].[Merch
    Pres Key].[Merch Pres Key])))
    ELSE
    NULL
    END
    /* Last year Active Products */
    Member [Measures].[LYCount]
    as
    CASE
    WHEN
    [Measures].[LYDemand] > 0
    THEN
    DistinctCount(([All Items].[IMD Id].[IMD Id],[All Merchandise Presentations].[Merch Pres Key].[Merch Pres
    Key], [All Items].[Style Name].CurrentMember, (StrToMember('[All Date].[Fiscal Month Name].&[201401]',CONSTRAINED).Lag(12)
    : StrToMember('[All Date].[Fiscal Month Name].&[201411]',CONSTRAINED).Lag(12))))
    ELSE
    NULL
    END
    /* Last to last Year Active Products */
    Member [Measures].[LLYCount]
    as
    CASE
    WHEN
    [Measures].[LLYDemand] > 0
    THEN
    DistinctCount(([All Items].[IMD Id].[IMD Id],[All Merchandise Presentations].[Merch Pres Key].[Merch Pres
    Key], [All Items].[Style Name].CurrentMember, (StrToMember('[All Date].[Fiscal Month Name].&[201401]',CONSTRAINED).Lag(24)
    : StrToMember('[All Date].[Fiscal Month Name].&[201411]',CONSTRAINED).Lag(24))))
    ELSE NULL END
    SELECT
    [Measures].[CYCount], [Measures].[LYCount], [Measures].[LLYCount],
    [Measures].[Proj Demand],[Measures].[LYDemand],[Measures].[LLYDemand]
    ON
    COLUMNS,
    Non
    Empty([All Items].[Demand Center Name].[Demand Center Name], [All Items].[Style Name].[Style Name])
    ON ROWS
    FROM
    (SELECT (StrToSet('[All Items].[Style].[ALL]'))
    ON COLUMNS
    FROM
    (SELECT (StrToSet('[All Items].[Demand Center].[ALL]'))
    ON COLUMNS
    FROM
    (select (STRTOSET('[All Items].[Merch Group].&[MG-110]'))
    on Columns
    FROM
    (SELECT (StrToSet('[All Merchandise Presentations].[Merch Pres Chnl Dkey].&[MPC-1]'))
    ON COLUMNS
    From
    [FMI Forecasting]
    WHERE {strToMember('[All Date].[Fiscal Month
    Name].&[201401]',CONSTRAINED) :
    StrToMember('[All Date].[Fiscal Month Name].&[201411]',CONSTRAINED)}
    Requirements are as follows:
    1. Distinct Count should not include products where Proj Demand is 0, when I am using Filter function to remove products with 0 demand, query is really slow and execution time goes up from 35- 40 secs to 8-9 Minutes.
    2. When we apply filter (parameters) Distinct Count should be in the context of filters( which are mentioned in the select statement like Style, Demand Center and Merch Group). Currently after applying filters count does not change.
    Thanks for help.

    Hi Skd78,
    Thank you for your question. 
    I am trying to involve someone more familiar with this topic for a further look at this issue. Sometime delay might be expected from the job transferring. Your patience is greatly appreciated. 
    Thank you for your understanding and support.
    Regards,
    Charlie Liao
    TechNet Community Support

  • How do I solve this distinct count problem?

    Hello experts,
      So, I have an OBI report (table view).  I needed to get the percentage difference btn 2 columns, I did. Then I had to summarize difference in 4 buckets (0-15, 16-30, 31-50, >50%); I did (case statement). NOW,  I need to summarize(distinct count) the above buckets based on Store numbers for each day.
    Basically, if the difference is btn(0-5%) and I have 5 stores then I need to see 5 stores separately. The problem I am having when I do the distinct count instead of having separate counts for each bucket I am getting the total.  I see the buckets summarized, but the store column is showing the total number of all(we have about 700 stores) instead of breaking down the count for each bucket.  In the stores column I am using the distinct count function, I don't know if the problem is here or the case statement for buckets. I don't know either OBIEE is able to do what I trying to do, since I have yet to do this kind of function.  I have gotten few leads on my first post,  so far none of them have worked.
    As always, your insights are highly appreciated,

    Instead of using Distinct Count in Aggregation Rule,Try using in Column Formula.
    Let me know if u need any help on this.
    Thanks,

  • Distinct count of dimension business key in fact table

    In my cube I have a fact table which joins to a patient dimension.  The patient dimension is a type 2.  What I would like to do is get a distinct count of patients who have records in the fact table.   The business key in the patient dimension
    is the PrimaryMrn.  So a SQL query would look like this.
    SELECT count(distinct PrimaryMrn)
    FROM EncounterFact e
    INNER JOIN PatientDim p
    on e.PatientKey = p.PatientKey
    Is it possible to do this via MDX?
    Thanks for the help.

    If you have to distinct count an attribute in a SCD 2, you might choose between:
    Denormalizing that attribute in the fact table, and the create a classical DISTINCT COUNT measure
    Use a many-to-many approach - see the "Distinct Count" scenario in the Many-to-Many White paper here:
    http://www.sqlbi.com/articles/many2many (for both Multidimensional and Tabular
    If you use Tabular, you might want to read also this pattern:
    http://www.daxpatterns.com/distinct-count/
    Marco Russo http://www.sqlbi.com http://www.powerpivotworkshop.com http://sqlblog.com/blogs/marco_russo

  • Distinct count for multiple fact tables in the same cube

    I'm fairly new to working with SSAS, but have been working with DW environments for many years.
    I have a cube which has 4 fact tables.  The central fact table is Encounter and then I also have Visit, Procedure and Medication.  Visit, Procedure and Medication all join to Encounter on Encounter Key.  The relationship between Encounter
    and Procedure and Encounter and Medication are both an optional 1 to 1.  The relationship between Encounter and Visit is an optional 1 to many.
    Each of the fact tables join to the Patient dimension on the Patient Key.  The users are looking for a distinct count of patients in all 4 fact tables.  
    What is the best way to accomplish this so that my cube does not talk all day to process?  Please let me know if you need any more information about my cube in order to answer this.
    Thanks for the help,
    Andy

    Hi Andy,
    Each distinct count measure cause an ORDER BY clause in the SELECT sent to the relational data source during processing. In SSAS 2005 or later, it creates a new measure group for each distinct count measure(it's a technique strategy for improving perormance).
    Besides, please take a look at the following distinct count optimization techniques:
    Create Customized Aggregations
    Define a Processing Plan
    Create Partitions of Equal Size
    Use Partitions Comprised of a Distinct Range of Integers
    Distribute the Hash of Your UserIDs
    Modulo Function
    Hash Function
    Choose a Partitioning Strategy
    For more detail information, please refer to the article below:
    Analysis Services Distinct Count Optimization:
    http://www.microsoft.com/en-us/download/details.aspx?id=891
    In addition, here is a good article about SSAS Best Practices for your reference:
    http://technet.microsoft.com/en-us/library/cc966525.aspx
    If you have any feedback on our support, please click
    here.
    Hope this helps.
    Elvis Long
    TechNet Community Support

  • 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

  • SQL DISTINCT COUNT IN DATE RANGE

    Dear All
    Thanks for your attention.
    A table is storing the task summary of each order
    e.g.
    Date                            | Order Number    | Task Number
    2015-01-01 00:00:01   | ABC123456        | JOB001
    2015-01-01 00:01:02   | ABC123456        | JOB002
    2015-01-01 00:10:02   | ABC123444        | JOB001
    2015-01-01 10:12:59   | ABC123456        | JOB002   (Since the job002 is not done correctly, need to work again)
    2015-01-01 18:20:05   | ABC888888        | JOB001
    2015-01-01 20:22:42   | ABC789456        | JOB001
    2015-01-01 21:02:11   | BBB121212        | JOB002
    I would like to write a single query that get the distinct count of order number in sepcific date range
    result as expected in three columns:
    2015-01-01
    task_number            | AM | PM
    JOB001         | 2    | 2
    JOB002         | 1    | 1
    explain the figures here:
    JOB001 AM = 2 (ABC123456, ABC123444)
    JOB002 AM = 1  (two records of ABC123456 count as 1 since we would like to know the number of orders)
    JOB001 PM = 2  (ABC888888, ABC789456)
    JOB002 PM = 1  (BBB121212)
    I wrote a query get similar result but the count of order is not distinct
    SELECT task_number,
    AM=SUM(CASE WHEN date >= ('2015-01-01 00:00:00') AND date < ('2015-01-01 12:00:00') THEN 1 ELSE 0 END),
    PM=SUM(CASE WHEN date >= ('2015-01-01 12:00:00') AND date < ('2015-01-02 00:00:00') THEN 1 ELSE 0 END)
    FROM MyTable
    WHERE task_number = 'JOB001'
    Could anyone advise how to enhance this query to let the result become disintct of order number?
    Many Thanks,
    swivan

    Try
    select task_number,
    count(distinct case when datepart(hour, [date]) >=0 and datepart(hour, [date]) < 12 then [OrderNumbers] END) as AM,
    count(distinct case when datepart(hour, [date]) >=12 and datepart(hour, [date]) < 24 then [OrderNumbers] END) as PM FROM myTable
    GROUP BY Task_Number
    For every expert, there is an equal and opposite expert. - Becker's Law
    My blog
    My TechNet articles
    Thank you very much,  short and good answer

  • 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

  • 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 Function-how to use properly

    Hello,
    I am new to using forums & have only been using Crystal since May of 2009, so i hope i do this correctly & provide the appropriate information.  i've looked for this answer in what's been posted but cannot find it.  Some things i've read I don't really understand.  I only know how to use the functions that are in the software, i don't know how to write them myself (i think that's when people have referred to SQL code or basic syntax)
    I have CR Professional, version 11.0.0.1282 (Crystal Reports XI).
    I work at a county health dept and we have a annual medicaid cost report,  I am linking Crystal to our EMR billing module.  i have my report sorted by insurance, ie medicaid, bcbs, abw, hpm etc.  and within each ins group i have the clients ID, DOS (date of service), procedure code, charge amt, ins pmt & patient pmt.  i have totaled the charges & pmts for each group-works fine.  i even have been able to create the formula to adj out the duplicate entries in the billing module (a service was entered wrong then adjusted out then re-entered correctly-without my formula crystal was pulling both these records and adding them to total charges.)
    Where my problem lies and what my question is:  I need to count encounters, an encounter is the visit, but each visit could have 2 or more procedure codes.   So this results in multiple lines on my report for one visit, which i want for the charges to add correctly, but it makes my visit count to high. So I read about the distinct count function, of which there are three listed & i'm having a hard time understanding the differences.  What i tried is: a distinct count of the acct ID-so the same acct ID's are only counted the one time.  But some clients see us more than once per year, meaning the acct ID is the same but the DOS is different.  For this client that would be 2 visits.  But crystal is counting this as 1.
    Saying what i want to do is this:  Count as 1 when the acct ID and DOS are the same.  I've tried using the different distinct counts but when i check my formula it always has errors.  So I'm sure my lack of knowledge is what's holding me up-i fully believe crystal can do this.
    Any help would be greatly appreciated.

    I create a dummy table, set up acc_id and DOS and Charge.
    Created a running total
    Summarized acc_id
    Type of summary Count
    Evaluated using a formula
         <> previous ()
    and reset on ACC_ID
    My groups were sorted by acc_id and date
    where there were multiple visits on the same DOS my count was 0
    where the dos changed it would count accordingly.
    You may need to use two Running totals to get the complete picture.

  • 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

Maybe you are looking for

  • Error when maintaining GL Account for Revenue account determination in VKOA

    Hi all, I am getting the error "Entry V XXXX doesnot exist check your entry", when I try to maintain account assignment under one condition table in VKOA. This error doesnot come while maintaining account assignment for the same combination under a d

  • How do you create a .cdr file from Apple's DVDs?

    I'm generally pretty religious about backing up DVD media to .cdr files in Disk Utility. As I look the iWork DVD that I have doesn't show any way to do this in Disk Utility right now.

  • Upgrading Acrobat v.9.0 to v.9.5.4

    I have Adobe Acrobat v.9.0 installed on a computer that is not connected to the internet (running Win 7). I would like to manually update this software to v.9.5.4 . According to the Downloads page for Acrobat for Windows, there are several updates st

  • Problem reading csv file with special character

    Hai all, i have the following problem reading a csv file. 442050-Operations Tilburg algemeen     Huis in  t Veld, EAM (Lisette)     Gebruikersaccount     461041     Peildatum: 4-5-2010     AA461041                    1     85,92 when reading this lin

  • Generate report in pdf in rute specifics??

    Hi, I have a form whit a button to generate report in pdf, works fine, but i want that when the user press the button, a window opened and the user choose where want to save the pdf... I think that i need some libs but i dont know, and i dont know th