Query to aggregate data

Hi, I need some help coming up with a query for department analysis. I am providing test cases below. My data is currently being taken from a Oracle 10g materialized view. What I need to do is give a date interval and find out how many people were in each dept (over all depts that exist in the view) at the beginning and end of the interval. If a person was in more than 1 dept during that period, only the last one is considered. Also, how many new people were added to the company
For example, using the data below and 13-AUG-04 through 30-AUG-04, I would get:
Unit #Beg #End #New
18 0 0 1
33 1 1 0
56 0 0 0
70 1 1 0
71 1 1 0
The last two columns in the test table (First/Last) refer to the person's employment in the company. There will be for sure either Y/Y (if the person has one period of employment only) or both Y/N, N/Y.
Where I'm having problems is to keep track of both current departments as well as new to the company. Someone can be new to the company (evidenced by First='Y'), but if he 's only moving to a different department then he's not new to the company.
Thanks,
Rob
create table test_dept
dept number,
head varchar2(20),
wrkid number,
name varchar2(50),
unitid number,
startdate date,
enddate date,
firstentry char(1),
lastentry char(1)
insert into test_dept values(20812,'JONES',27264,'SMITH, Mary',71,to_date('09-AUG-04','DD-MON-YY'),to_date('11-AUG-04','DD-MON-YY'),'Y','N');
insert into test_dept values(20812,'JONES',27264,'SMITH, Mary',71,to_date('11-AUG-04','DD-MON-YY'),to_date('04-OCT-04','DD-MON-YY'),'N','N');
insert into test_dept values(20812,'JONES',27264,'SMITH, Mary',33,to_date('04-OCT-04','DD-MON-YY'),to_date('05-OCT-04','DD-MON-YY'),'N','N');
insert into test_dept values(20812,'JONES',27264,'SMITH, Mary',33,to_date('05-OCT-04','DD-MON-YY'),to_date('19-APR-05','DD-MON-YY'),'N','Y');
insert into test_dept values(20812,'JONES',27265,'SMITH, Jack',71,to_date('09-AUG-04','DD-MON-YY'),to_date('11-AUG-04','DD-MON-YY'),'Y','N');
insert into test_dept values(20812,'JONES',27265,'SMITH, Jack',33,to_date('10-AUG-04','DD-MON-YY'),to_date('05-OCT-04','DD-MON-YY'),'N','N');
insert into test_dept values(20812,'JONES',27265,'SMITH, Jack',33,to_date('05-OCT-04','DD-MON-YY'),to_date('20-APR-05','DD-MON-YY'),'N','Y');
insert into test_dept values(28022,'BABS',39220,'RUPERT, A',70,to_date('11-AUG-04','DD-MON-YY'),to_date('29-OCT-04','DD-MON-YY'),'Y','N');
insert into test_dept values(28022,'BABS',39220,'RUPERT, A',33,to_date('19-OCT-04','DD-MON-YY'),to_date('25-OCT-04','DD-MON-YY'),'N','N');
insert into test_dept values(28022,'BABS',39220,'RUPERT, A',33,to_date('25-OCT-04','DD-MON-YY'),to_date('23-NOV-04','DD-MON-YY'),'N','N');
insert into test_dept values(28022,'BABS',39220,'RUPERT, A',70,to_date('23-NOV-04','DD-MON-YY'),to_date('27-JAN-05','DD-MON-YY'),'N','N');
insert into test_dept values(28022,'BABS',39220,'RUPERT, A',33,to_date('08-FEB-05','DD-MON-YY'),to_date('13-JUL-05','DD-MON-YY'),'N','N');
insert into test_dept values(28022,'BABS',39220,'RUPERT, A',56,to_date('13-JUL-05','DD-MON-YY'),to_date('31-OCT-05','DD-MON-YY'),'N','Y');
insert into test_dept values(20812,'JONES',10000,'B',18,to_date('15-AUG-04','DD-MON-YY'),to_date('29-AUG-04','DD-MON-YY'),'Y','Y');

this?
var d1 varchar2(100)
var d2 varchar2(100)
exec :d1 := '13-AUG-04'
exec :d2 := '30-AUG-04'
select unitid,
sum( case when startdate <= to_date(:d1) and enddate >= to_Date(:d1)
            and nextstart >= to_date(:d2) then 1 else 0 end ) beg#,
sum( case when startdate <= to_date(:d2) and enddate >= to_Date(:d2) then 1 else 0 end ) end#,
sum( case when firstentry='Y' and startdate between to_Date(:d1) and to_date(:d2) then 1 else 0 end ) new#
from (
  select unitid, wrkid, name,
   startdate, enddate, firstentry,
   last_value(startdate) over (partition by wrkid order by startdate desc
      rows between unbounded preceding and 1 preceding) nextstart
  from test_dept
group by unitid
/you should have test data where a dept has different beg and end numbers.

Similar Messages

  • How to aggregate data in SQL Query

    Hi,
    I have Table1 field1 and field2. Combination of these fields form the key of this table.
    Next I have Table2 with field3 and field4. field1 is the unique key for this table.
    My query is:
    select T2.field4||','||T1.field2 from T1 inner join T2 on T1.field1 = T2.field3;
    In the result I want to aggregate the data by T2.field4
    How do I that? Please help
    Thanks in advance,
    Raja

    How to aggregate data in SQL Query By using aggregate functions and group by:
    SQL> select object_type, count(*), sum(decode(status,'VALID',0,1)) inv_obs
      2  from all_objects
      3  group by object_type;
    OBJECT_TYPE                     COUNT(*)              INV_OBS
    CONSUMER GROUP                         2                    0
    INDEX PARTITION                      970                    0
    TABLE SUBPARTITION                    14                    0
    SEQUENCE                             226                    0
    SCHEDULE                               1                    0
    TABLE PARTITION                      349                    0
    PROCEDURE                             21                    0
    OPERATOR                              57                    0
    WINDOW                                 2                    0
    PACKAGE                              313                    0
    PACKAGE BODY                          13                    0
    LIBRARY                               12                    0
    PROGRAM                                9                    0
    INDEX SUBPARTITION                   406                    0
    LOB                                    1                    0
    JAVA RESOURCE                        771                    0
    XML SCHEMA                            24                    0
    JOB CLASS                              1                    0
    TRIGGER                                1                    0
    TABLE                               2880                    0
    INDEX                               4102                    0
    SYNONYM                            20755                  140
    VIEW                                3807                   72
    FUNCTION                             226                    0
    WINDOW GROUP                           1                    0
    JAVA CLASS                         16393                    0
    INDEXTYPE                             10                    0
    CLUSTER                               10                    0
    TYPE                                1246                    0
    EVALUATION CONTEXT                     1                    0

  • Can I store only the aggregate data in OLAP cube

    Hi All,
    I know that the OLAP cubes store the leaf data and then builds the aggregate data on top of it and stores with in it. I have huge amounts of data ( like billions of data in my fact table and 6-8 dimension tables). If you keep the leaf data along with the agg data with in the cube would be too large to build.
    So I am thinking to have to store only the agg data within the OLAP cube and for the leaf data it should still read from the Relational tables. Something like Hybrid OLAP.
    (what I mean is
    1. create the dimensions and cube in the AWM on 11g.
    2. I will also specifiy the levels that I want the agg data to be calculated and stored in the OLAP cube.
    (what I want is
    1. I want to store only the agg data in the cube and leaf data still in the relatlional tables.
    2. when I read the cube and drill down to the leaf level , it should fetch the leaf level data.
    Is this possible in Oracle OLAP, if yes please provide some pointers
    Thanks
    S

    First you should try out storing and aggregating data to atleast see if the cube-loading time, query-time and AW-size is within acceptable limit or not. 11gOLAP especially 11gR2 OLAP is very efficient on all three fronts.
    Regarding specifying levels, you can either use Cost-based-aggregation and pick the %age that should be pre-aggregated OR you can use Level-based-aggregation and pick the levels from each dimension that should be pre-aggregated.
    Try these out before venturing into anything else. You will be surprised by the results. There are other ways to store the data in smaller multiple-cubes and joining those cubes through formulas. Make sure you don't mistake an attribute for a dimension.
    Not sure what you mean by just storing aggregated data in olap cubes. You can just do a SUM .. GROUP BY .. of relational data before loading it into olap cubes. For example, if you source data is at DAY level, you can SUM.. GROUP BY .. at MONTH-level and then load month-level data into olap cubes where leaf-level is month-level.
    The sql view (used by reporting tools) could then be a join between month-level "olap" data and "day-level" relational data. When you are drilling-down on the data, the sql view will pick up data from appropriate place.
    One more thing. Drill-Thru to detail data is a functionality of reporting tools also. If you are using OBIEE or Discoverer Plus OLAP, then you can design the reports in a way that after you reach the olap leaf-level, then it will take the user to a relational detail-report.
    These are all just quick suggestions (on a Friday evening). If possible, you should get Oracle OLAP Consulting Group help, who can come up with good design for all your reporting needs.

  • How to aggregate data with BI Publisher using an OBIEE analysis

    Hello,
    I'm new with BI Publisher, and I have a concern about the ability for BIP to aggregate data.
    I am creating a data source from an OBIEE analysis containing the columns "Year", "Month", and "Revenue".
    I want to use this source for 1 report containing several pages. One of the page has a simple table displaying only the Year and the Revenue.
    But I get as many rows as number of months is the year.
    And I cannot find any way to have the data aggregate inside my PIB table.
    Can someone help me finding the solution?
    Many thanks in advance

    Hi,
    Unfortunalty BIP doesn't aggregate anything, like the BI server does. It will always show data on the lowest level.
    If you use a query on the BI-server let the BI server do the aggregation and just remove the "Month" column. If you don't want to remove it from your OBI analysis, copy the logical SQL from this analysis to BIP. And select OBIEE as a datasource.
    Then remove month from your query.
    Regards, Machiel

  • Summary Vs. Aggregate Data

    Hi,
    Could anyone tell me the difference between summary and aggregate data?
    Thanks in advance,
    AJ

    yes.
    http://books.google.com/books?id=aIs8drBVdaoC&pg=PA355&dq=%22Before+you+can+query+SSAS+from+your+web+application%22&hl=en&sa=X&ei=z_HUUtD2L4juoASzuYGIBw&ved=0CEgQ6AEwAA#v=onepage&q=%22Before%20you%20can%20query%20SSAS%20from%20your%20web%20application%22&f=false
    Tatyana Yakushev [PredixionSoftware.com]
    Download Predixion Insight 3.0 - World class predictive platform for big data

  • Not sure if this is the right place...but is there any aggregate data repository/dictionary out there?

    And what I mean is...Is there any aggregate data dictionary out there that tells you how long and what type a data column should be?
    For example...Medical Provider Name...what is the normal length for something like this? Provider ID? Tax ID? Address Line 1? City? State?...Etc...
    Is like EDI X12 considered the Bible of Data Dictionaries? Yet you have to pay for that don't you? Is there anything else I can reference???
    Thanks for your review and am hopeful for a reply.
    PSULionRP

    Provider ID is well defined:
    "National Provider Identifier Standard (NPI)
    The National Provider Identifier (NPI) is a Health Insurance Portability and Accountability Act (HIPAA) Administrative Simplification Standard. The NPI is a unique identification number for covered health care providers. Covered health care providers and
    all health plans and health care clearinghouses must use the NPIs in the administrative and financial transactions adopted under HIPAA. The NPI is a 10-position, intelligence-free numeric identifier (10-digit number). This means that the numbers do not carry
    other information about healthcare providers, such as the state in which they live or their medical specialty. The NPI must be used in lieu of legacy provider identifiers in the HIPAA standards transactions."
    LINK:
    http://www.cms.gov/Regulations-and-Guidance/HIPAA-Administrative-Simplification/NationalProvIdentStand/index.html?redirect=/NationalProvIdentStand/
    Kalman Toth Database & OLAP Architect
    SQL Server 2014 Design & Programming
    New Book / Kindle: Exam 70-461 Bootcamp: Querying Microsoft SQL Server 2012

  • Looking at aggregate data

    Hi Guys,
    I created an aggregate from a cube, there is a way to see the aggregate data as I see the cube or DSO data.
    Thanks

    Hi,
    The active aggregate that is filled with data can be used for reporting. If the aggregate contains data that is to be evaluated by a query, the query data is read automatically from the aggregate.
    For the more information:
    http://help.sap.com/erp2005_ehp_04/helpdata/EN/1a/f1fb411e255f24e10000000a1550b0/frameset.htm
    regrads...KP

  • Getting data in a query on last date of all previous months

    Dear Experts,
    I need your help with a query.
    I am trying to create a query which when run should pick the number of Open Sales Order on the last date of all the previous months from the start of company.
    I could create the query for fetching the required data on last day of the previous month, say today is 25th June 2014, so my query only fetches data for May 31st 2014 but I need data for all previous month, May 31st 2014, April 30th 2014, March 31st 2014 & so on.
    Please advise how to achieve this is SQL query.
    Thanks & regards,
    Nitin

    Hi,
    Try this:
    Select *
    from(
    SELECT T0.[DocNum] as #,t0.cardcode as C, t0.docdate
    FROM ORDR T0
    WHERE T0.[DocStatus] = 'o' and T0.[DocDate]  = CONVERT(VARCHAR(10), DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,getdate())-1,0)),10) OR T0.[DocDate]  = CONVERT(VARCHAR(10), DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,getdate())-2,0)),10) or T0.[DocDate]  = CONVERT(VARCHAR(10), DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,getdate())-3,0)),10) or T0.[DocDate]  = CONVERT(VARCHAR(10), DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,getdate())-4,0)),10) or T0.[DocDate]  = CONVERT(VARCHAR(10), DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,getdate())-5,0)),10) or T0.[DocDate]  = CONVERT(VARCHAR(10), DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,getdate())-6,0)),10) or T0.[DocDate]  = CONVERT(VARCHAR(10), DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,getdate())-7,0)),10)
    group by t0.cardcode,docdate,T0.[DocNum]) S
    pivot
    (count(#) for c in([cvt01],[cvt02],[cvt03],[cvt04],[cvt05],[cvt06],[cvt07],[cvt08],[cvt12])) P
    Note: Replace Cvt01,02...with your customer code.
    Thanks & Regards,
    Nagarajan

  • POWER QUERY Get External Data From File From Folder (Excel 2013)

    Hi,
    Beginner's question :
    What could be the use of the query on a folder : we just get a list of files with their path. What can we do with that?
    Thanks

    Hi,
    Do you want to combine data from multiple Excel Files in the same folder path into one table? If I understand correct, we can add a custom column to import the data.
    After we getting a list of files with their path, the Query Editor window will activate to show you a table containing a record for each file in the chosen directory. These will provide our function with the needed FilePath and FileName parameters. 
    Function sample: File name([Folder path],[Field name]
    For more detailed steps, please see the article:
    http://datapigtechnologies.com/blog/index.php/using-power-query-to-combine-data-from-multiple-excel-files-into-one-table/
    Please Note: Since the web site is not hosted by Microsoft, the link may change without notice. Microsoft does not guarantee the accuracy of this information.
    George Zhao
    TechNet Community Support
    It's recommended to download and install
    Configuration Analyzer Tool (OffCAT), which is developed by Microsoft Support teams. Once the tool is installed, you can run it at any time to scan for hundreds of known issues in Office
    programs.

  • Data driven subscription query returns no data

    We have a data driven subscription on SSRS 2008 R2. The columns in the query are tied to one or more parameters of the report. When we run the subscription and if the query does not return any rows, I was hoping that the subscription will not start; however,
    instead, to my surprise, I got error stating..."Parameter XYZ value can't be null". How to avoid this error and keep subscription from running in this situation? 
    Example: I have a report that required employeeID as a parameter. I have a query (step 3: data driven subscription) that fetches employee ID based on some criteria. If there is no row returned by the query; It throws error on report stating "Parameter
    EmployeeID can't be null."
    Nehal Jain

    Hello Nehal -
    Try adding a UNION ALL to your parameter dataset query like
    UNION ALL SELECT NULL AS EmployeeID , ..
    Just check accordingly. I ll revert again based on this , got a priority now.
    Happy to help! Thanks. Regards and good Wishes, Deepak. http://deepaksqlmsbusinessintelligence.blogspot.com/

  • Web Analysis Error -- Error while executing query and retrieving data

    Regarding Web Analysis:
    We have a number of reports that we created. yesterday they were all working fine. today we try to open them and most are generating an error.
    The error is:
    Error while executing query and retrieving data.; nested exception is:
    com.hyperion.ap.APException: [1033] Native:
    1013033[Thu Oct 22 09:08:17
    2009]server name/application name/database name/user name/Error91013033)
    ReportWriter exit abnormally
    Does anyone have any insight into what is going on?
    My version information is:
    Hyperion System 9 BI+ Analytic Administration Services 9.3.0.1.1 Build 2
    Web Analysis 9.3.0.0.0.286
    Thanks in advance for your help.
    DaveW

    Hi,
    And also click on check option by opening the query in Query designer,as Mr . Arun suggested.
    And if you get any error in checking, see the long message(detail).
    With rgds,
    Anil Kumar Sharma .P

  • Select query to read data from a view

    Hi friends,
    We have been using a query to read data from a custom view which used to work perfectly. Now the program sits at that select query forever. We are able to extract same data from se16. Not sure what could be the problem.
    Thanks in advance.

    Dev
    Have a look at the Table Index for the tables involved in the View... I think there is some change in the Indexes.. (Add / Remove / Change)
    Thanks
    Amol Lohade

  • Error when executing a query on master data

    Hi Friends,
    When I execute a query fon Master Data Characteristic infoObject ( 0BPARTNER ) from BEx Analyzer I got the below error. 0BPARTNER contains 15 attributes. I am getting the below error only for this query. Rest all other queries are working good with the same BEx Analyzer.
    <b>An error occured in the communication with the BW Server.
    Due to this connection has to be closed.</b>
    <b>Detailed Description:
    The system is configured incorrectly.</b>
    Please tell me what could be the problem? How to overcome this?
    Thanks,
    Sasi

    Hi Arun,
    Before the execution of query I did that. And it was ' Query is Correct'.
    Any more ideas?
    Thanks,
    Sasi.

  • How to use a query in matrix data retrive

    hai  everybody
    how to use a query in matrix data retrive...
    pls ..

    If u have created a UDT to store the data then U can retrive the data through recordset.
    oRecordset.doquery("SQL Statement")
    If u have taken the DB Data source to Manipulate then
    then type
    oMatrix.flushtoDataSource
    then
    U can retrive the data through DB Data source.
    -Manmath

  • Query regarding the data type for fetcing records from multiple ODS tables

    hey guys;
    i have a query regarding the data type for fetcing records from multiple ODS tables.
    if i have 2 table with a same column name then in the datatype under parent row node i cant add 2 nodes with the same name.
    can any one help with some suggestion.

    Hi Mudit,
    One option would be to go as mentioned by Padamja , prefxing the table name to the column name or another would be to use the AS keyoword in your SQL statement.
    AS is used to rename the column name when data is being selected from your DB.
    So, the query  Select ename as empname from emptable will return the data with column name as empname.
    Regards,
    Bhavesh

Maybe you are looking for

  • Not able to get correct BIP report output in case of more than 6000 records

    Hi, When we are trying to generate the BIP report in siebel 8.1.1, for the list of records whose count exceeds 6000 records, we are gettin a error as "Error <?> invoking method "<?>" for Business Service "<?>"(SBL-OMS-00203) W have done all the optim

  • Sales Returns with batch split.

    12.10.10 Hi friends, I have created a sales return against invoice with multiple batches for a BOM item.  During returns the returns have created individual lines for each of the batch and the components are also available as per sales bom. The compo

  • Photoshop won't open DNG files or says get are absent?

    Suddenly, ,most of my photos show up in Bridge as DNGs and when I try to open them with PS CC I get one of two messages: PS does not recognize this format or that the photo is missing. But when I use another program, it shows the photo.

  • SIGSEGV (0xb) - How to troubleshoot?

    We are trying to identify what is causing segmentation fault and particularly how to troubleshoot it? The following exception is thrown on our server when under stress, which kills all running java processes. # SIGSEGV (0xb) at pc=0x0000000000000038,

  • LR4: auto-assigned placenames not written to XMP on export?

    When pinning a photo to the map, and get the GPS coordinates into metadata. I also get information in the IPTC fields for ISO Country Code, Country and State/province, but they are marked in italics and with a grey-coloured typeface. I use DNG raw fi