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

Similar Messages

  • 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

  • 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

  • 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

  • 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

  • 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

  • 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

  • Problem In Query PLD

    Hi All
    We have problem while generating the query pld in SAP B1 2005 PL 34. We have given query for Goods Receipt PO with batch/serial no details. The details of batch no and serial no is working properly. When we execute the query if query pld comes to second page it is not displaying the details of GRN PO no, date, etc...
    Our customer require GRN PO details in the suceessive pages. How to achieve this?
    Thanks in Advance

    hi Consultant,
    Where did you put the GRN PO No, Date and Details?
    Did you Use of Group by method in Repetetive Area (or) Repetetive Area Footer?
    Do you want GRN PO No., Date and Other GRN Details in Header Level?
    Try this,
    1. Select GRN No. in Row Level and Copy (GRN No.) Field ID on Properties Area Window.
    2. Create 1 Formula Field in Page Header and Put GRN No. Field ID.
    Regards,
    Madhan.
    Edited by: Madhan Babu C on Aug 3, 2009 1:36 PM

  • 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 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

  • MeasureExpression property - Is there a possibility to implement distinct count with exclude empty?

    I have a measure which needs to have distinct count aggregation with exclude empty.
    Is there a possibility to specify MeasureExpression property to achieve the same? I have set the aggregation of the measure to none and I have typed the following function,
    Count(Distinct(Column_name),EXCLUDEEMPTY)
    where as the measure reads 0(zero) upon processing. Is there any other way to achieve this?
    The data feed has nulls included too for the column which this is to be achieved, which cannot be modified in the data level.
    Regards,
    Kantha Girish

    Hi Kantha,
    According to your description, you want to implement the distinct count aggregation, right? In this case, we can use a query like
    count(nonempty([DimName].[HierarchyName].[LevelName].members,[Measures].[MyMeasure]))
    Here are some blogs about how to implemet distinct count aggregation, please refer to the link below.
    http://blog.sqltechie.com/2009/09/distinctcount-analysis-service.html
    http://richardlees.blogspot.com/2008/10/alternative-to-physical-distinct-count.html
    If I have anything misunderstood, please point it out.
    Regards,
    Charlie Liao
    TechNet Community Support

  • 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.

Maybe you are looking for

  • How do I turn off pop up blocker on my macbook air

    how do I turn off a pop up blocker on my macbook air?

  • Dual 27" iMacs - one as a monitor?

    This may sound like a stupid question, but I want to be sure before I go buying a cable. I am in a unique situation...I just got clearance to work from home at my job (as a graphic designer), and I bought a 27" iMac Core i5. Well, work also got new 2

  • After purchasing and downloaded GarageBand software, It won't work and start over and over to download the software

    After purchasing and downloading GarageBand on App Store the software won't start and switch to download over and over the software. It's virtually impossible to reach someone from Apple for support grrrrrrr.... So can someone could kindly give me a

  • Job - Corpus Christi TX

    Hello, Probado Technologies Small 8a Company is looking for an Authorware developer in Corpus Christi TX. Experience: Macromedia Authorware Courseware Author needed to create interactive computer-based training for the Navy. 2-3 Years of experience.

  • BIND-PARAMS HELP PLEASE IN XSQL

    Hello All, I have 3 tables these are track, album and a join table called albumTrack I need to use bind-params to link album and track up with the join table so that when i select an album I can view all the tracks associated with that album. Here is