One record per person, either the min year or year max

Asked to show one record per person according to the following criteria: the number of years between the startyear and the courseyear is less than 4 use of the first year of course if if the number of years between the startyear and the courseyear is greater than 4 use the last (most recent) courseyear. The other problem with the data over time, the courseno has changed, but is still considered as the same course. Here are examples of data (with declaration) and the SQL code that I started to build.
with firstlast as
(
select '12345' as id, 2005 as startyear, 2006 as courseyear, 'SCI221' as courseno from dual union
select '12345' as id, 2005 as startyear, 2007 as courseyear, 'SCI221' as courseno from dual union
select '23456' as id, 2008 as startyear, 2009 as courseyear, 'SCI221' as courseno from dual union
select '23456' as id, 2008 as startyear, 2013 as courseyear, 'SCI226' as courseno from dual union
select '34567' as id, 2010 as startyear, 2011 as courseyear, 'SCI221' as courseno from dual union
select '34567' as id, 2010 as startyear, 2012 as courseyear, 'SCI221' as courseno from dual
)
select id, startyear, courseyear, 
min(courseyear) over (partition by id) as minterm, max(courseyear) over (partition by id) as maxterm,
         max(courseyear) over (partition by id) - courseyear   as lagterm,
         CASE WHEN max(courseyear) over (partition by id) - (courseyear) > 2 THEN 3
                  ELSE 0
         END  as lagtermno,
courseno
 from firstlast         
This is the expected result.
ID      STARTYEAR     COURSEYEAR     COURSENO
12345    2005             2006             SCI221
23456    2008          2013              SCI226
34567    2010             2011              SCI221
-----------------------------------------------------------------------------
BANNER
Oracle Database 11 g Enterprise Edition Release 11.2.0.2.0 - 64 bit Production
PL/SQL Release 11.2.0.2.0 - Production
CORE Production 11.2.0.2.0
AMT for Solaris: 11.2.0.2.0 - Production Version
NLSRTL Version 11.2.0.2.0 - Production

Hello

user1069723 wrote:
... For cases where there is more than one line per person:

If the difference between the year of course and the start year is 3 or less choose all of the line which was the first year of classes.

If the difference between the year of course and the start year is greater than 3, then select the entire line that is the last year of course.

Oh, you want the first or last line.

This is an example of a Query of Top - N . Here's a way to do it:

WITH     got_analytics     AS
(
     SELECT     f.*
     ,     ROW_NUMBER () OVER ( PARTITION BY  id
                               ORDER BY          courseyear
                       )                      AS a_num
     ,     ROW_NUMBER () OVER ( PARTITION BY  id
                               ORDER BY          courseyear     DESC
                       )                      AS d_num
     ,     MAX (courseyear) OVER (PARTITION BY id)
           - MIN (startyear)      OVER (PARTITION BY id)     AS year_dif
     FROM  firstlast  f
)
SELECT       id, startyear, courseyear, courseno
FROM       got_analytics
WHERE       1 = CASE
               WHEN  year_dif > 3
            THEN  d_num
            ELSE     a_num
           END
ORDER BY  id
;

The typical top - N query is to calculate ROW_NUMBER (in ascending or descending) in a subquery and then by using the WHERE clause of the main query to get only the rows where this number is<=>
This top - N query is somewhat different, because if we are ascending to descending order may vary the partition in the partition. In the above query, we calculate the ROW_NUMBER in both directions and then, in the main query, decide whether we will use the bottom line number or decreasing the number.

Tags: Database

Similar Questions

  • HELP I'm a data merge and it gives me only one record per page!

    I really need help here.  I do a fusion of data and that you have selected the options to make more than one record per page, but instead, it is to its own page, merge.  Can someone tell me what I'm missing?

    CS6 seems to have some difficulty to know when there is enough space. The simple solution is to the margins on the right and down the 0 value in the layout options.  And several record preview is known to be buggy. It is best to take a leap of faith and the merger without preview or cancel after you have previewed and before the actual merger.

  • InDesign, fusion and mailing: change of the function "record per page.

    I am a new user of InDesign and have a problem that I spent several days trying to correct.  In short, we are 'attempt' create our product catalog by importing our QuickBooks data (such as a csv or txt file).

    I think I've isolated the problem to the installation of "records per page.

    For some reason any, when I open the .csv or .txt file (window > utility > data merge).

    Since the Panel to merge the data, I select the source file, and the box 'Create a merged Document' begins.

    However, the ID is defaulting to one record per page.  When I open the presentation of Multiple recording tab I get... "optiion disabled because only the record is selected... »

    I spent several days of reading every post I could find on this and I go brain dead.  Can someone help me out here?

    Thanks in advance for your time and attention.

    Hi Jeffrey,.

    Thank you for taking the time to put video capture whole.  Unfortunately, he is suspended until about a third of the way through...

    What he shows is open a blank sheet, opening Pages and opening and then merge the data...

    As you can see on the below two screen captures, I don't even get the ability to merge data into my Pages dialog box...?

    So, I wonder if I have a problem with my installation ID or some corrupted how a configuration or default file... Hmmmm

    Thank you again, thank you for your help.

    Post edited by: Everwood farm

    I have re-installed ID - probably didn't need to do - and delete the cache files and the Setup program that was the culprit.  Now works perfectly... go figure :-)

  • Data merge, its is possible to display the 5 records per page?

    I have no problem doing mergers of data.  Still, they seem to only show only one record per page, but is there a way to display multiple records per page?

    Read the help for an explanation full, then come back here with specific questions if you still have problems...

    Basically, set you up a single instance of the placeholders field on your page, then select several records per page in the merge options. You cannot specify a number directly, but ID will be reprduce as many records on the page all items using the spacing settings you set up, then you want to add an empty block size required to get your five instances with zero spacing and group them with field labels.

  • Script to place the image folder to 100%, one image per page?

    I'm looking for a script that can drop a folder of images in an ID doc to 100%, one page per image, with the name of the file image below. I tried various Board-contact scripts, but these scale images to fit the page. I need the images to be placed at 100%, so a customer can view them to their exact size.

    Any help would be much appreciated. Thank you!

    Try this,

    var doc = app.activeDocument;
    var w =doc.documentPreferences.pageWidth;
    var h = doc.documentPreferences.pageHeight;
    doc.viewPreferences.rulerOrigin = RulerOrigin.pageOrigin;
    var _folder = Folder.selectDialog("Select a folder");
    var _files = _folder.getFiles();
    
    for(var i =0;i<_files.length;i++)
    {
            if(_files[i] instanceof File)
            {
                    var image = doc.pages.item(-1).place(_files[i]);
                    var gb = image[0].parent.geometricBounds;
                    var imageheight = gb[2] - gb[0];
                    var imagewidth = gb[3] - gb[1];
                    image[0].parent.geometricBounds = [(h-imageheight)/2,(w-imagewidth)/2,(h-imageheight)/2+imageheight,(w-imagewidth)/2+imagewidth];
                    image[0].parent.fit(FitOptions.CONTENT_TO_FRAME)
                    doc.pages.add(LocationOptions.AT_END);
                }
        }
    doc.pages.item(-1).remove();
    

    Kind regards

    Cognet

  • Definition of ethnicity to group a rec per person based on several conditions

    Hello

    The final results will be used in a report and the table. A new category for ethnicity has been added to the database.
    For this reason, the field that we use to report is no longer available. I've implemented a query
    identify a record per person for ethnicity codes. The rules are if the person has a record ID as
    Hispanic who use little matter that they have more than one record. If the person is Hispanic,
    Then identify which category they are. If they have only a record (or multiple records in the same category),
    Code for the main category. If they have more than one record in all categories (except Hispanic), then count
    them as multi-ethnic.

    Because the table is large and is joined with other tables for the various reports, I would like to know
    If there is a way more efficient and parallel to write the sql statement. In addition, for the future, they
    intend to request a report that will decompose the multiethnic in different categories to display a chart.
    I thought that I would need pivot 'horizontally', or could happen "vertically," the way that the
    underlying table is.

    In the sample data:
    1st person has two records Hispanic and European; count under "Hispanic."
    2nd person has two white records and Western Europe; count as 'White '.
    3rd person has two records Indian and African; count under "multiethnic".
    4th person has a record of the Sioux; count under "American Indian or Alaska Native".


    Here is a table of sample data:
    CREATE TABLE ETHTEK
    (
      ID             VARCHAR2(5 CHAR),
      ETHCODE        VARCHAR2(1 CHAR),
      ETHGROUP_CODE  VARCHAR2(3 CHAR),
      ETHGROUP       VARCHAR2(30 CHAR)
    );
    
    INSERT INTO ETHTEK
    (ID, ETHCODE, ETHGROUP_CODE, ETHGROUP)
    Values
    ('11111', '5' ,'SEU', 'Southern European');
    INSERT INTO ETHTEK
    (ID, ETHCODE, ETHGROUP_CODE, ETHGROUP)
    Values
    ('11111', 'H', 'SAM', 'South American');
    INSERT INTO ETHTEK
    (ID, ETHCODE, ETHGROUP_CODE, ETHGROUP)
    Values
    ('11121', '5', 'WEU', 'Western European');
    INSERT INTO ETHTEK
    (ID, ETHCODE, ETHGROUP_CODE, ETHGROUP)
    Values
    ('11121', '5', '5', 'White');
    INSERT INTO ETHTEK
    (ID, ETHCODE, ETHGROUP_CODE, ETHGROUP)
    Values
    ('11122', '3', 'AF', 'African');
    INSERT INTO ETHTEK
    (ID, ETHCODE, ETHGROUP_CODE, ETHGROUP)
    Values
    ('11122', '2', 'IND', 'Indian');
    INSERT INTO ETHTEK
    (ID, ETHCODE, ETHGROUP_CODE, ETHGROUP)
    Values
    ('11159', '1', 'SIO', 'SIOUX');
    Note: for do not need to create another table, I've hardcoded the translation of the description in the box instructions
    in the following query. The actual query uses a lookup table.

    Here's the sql code: (for some reason, in my preview, the upper/lower that the symbols are not, so put a comment on the lines that should be not equal in case they don't show up when posting)
    WITH e AS                                                       --Ethnicity
            (SELECT DISTINCT id,
                             ethcode, 
                             ethgroup_code
                             ethgroup
                        FROM ethtek
            ),
            h AS                                                        --Hispanic
            (SELECT id, ethcode
               FROM e
              WHERE ethcode = 'H'),
            nhm AS                                  --Non Hispanic or Multi Ethnic
            (SELECT DISTINCT id, ethcode
                        FROM e
                       WHERE ethcode <> 'H'),             -- Not Equal 'H'
            nh AS                                                   --Non Hispanic
            (SELECT id,
                    CASE
                       WHEN COUNT (*) OVER (PARTITION BY id) >
                                                                 1
                          THEN 'M'
                       ELSE ethcode
                    END AS ethcode
               FROM nhm
              WHERE ethcode <> 'H')                     -- Not Equal 'H'
       SELECT id, ethcode,
              CASE
                 WHEN ethcode = 'H'
                    THEN 'Hispanic or Latino'
                 WHEN ethcode = '5'
                    THEN 'White'
                 WHEN ethcode = 'M'
                    THEN 'Multi-Ethnic'
                 WHEN ethcode = '1'
                    THEN 'American Indian or Alaskan Native'
                 ELSE ethcode
              END AS ethnic_desc,
              CASE
                 WHEN ethcode = 'H'
                    THEN '4'
                 WHEN ethcode = '4'
                    THEN '5'
                 WHEN ethcode = '5'
                    THEN '6'
                 ELSE ethcode
              END AS old_ethnicity_code
         FROM (SELECT DISTINCT h.*
                          FROM h
               UNION
               SELECT DISTINCT nh.*
                          FROM nh LEFT OUTER JOIN h ON nh.id =
                                                                      h.id
                         WHERE h.id IS NULL) eth;
    What is the result of the query:
    Row#     ID     ETHCODE     ETHNIC_DESC     OLD_ETHNICITY_CODE
    1     11111     H     Hispanic or Latino               4
    2     11121     5     White                         6
    3     11122     M     Multi-Ethnic                    M
    4     11159     1     American Indian or Alaskan Native     1
    Thus, on 7 disks, we only have 4 people once.

    This is the result of summary query (not included):
         Group               Total
    American Indian/Alaskan Native     1
    Hispanic               1
    White                    1
    Multi-Ethnic               1
    Total                    4

    Hello

    Thanks for posting the CREATE TABLE and INSERT.
    The main reason for this is to allow people who want to help you recreate the problem and test their ideas. If you post statements that don't work, it defeats the purpose.
    Please check all the code before you post. Each of the INSERT statements has a lack of parentheses or quotation (usually two).

    If you have a parent-child relationship within the gorrace; some lines are parents of other lines, and you want the children to inherit traits from their parents.
    What you posted is the usual way to the relational database for handling that: a self-join. I don't see any obvious ways to make the self-join more quickly.
    You can avoid the self-join in your query if you are willing (and able) to denormalize the table and copy the traits inherited from their parents to their children. This looks like the kind of table that won't change very often, in order to maintain the standard table shouldn't be a big project. However, if the table has only 56 lines, so whatever you do with it, maybe not a great impact on the overall performance of the query.

    If you want to improve performance, a more scientifically to go about this is to know what that bottlenecks in the existing query and remedy.
    See these discussions on how to report a tuning issue:
    When your query takes too long...
    HOW to: Validate a query of SQL statement tuning - model showing
    Then start a new thread, setting just about the request.

  • Number of records per column in each table

    Hi all

    I need to get the number of records by column for each table in a schema.

    Is there a way I get the list of columns in each table in a schema and get the number of records per column where the count > 0?

    We have oracle 10g

    Thank you

    Smidreb wrote:
    You are right, but we're going to run the script as soon as we move

    the script below gives me a correct result.

    If it works well for you, then it works OK for me.

    Realize that Oracle is that I/O block-level.
    As a general rule, any LINE is a single block.
    Realize that is 1 column "count (*)" is correct, then all the columns in the same row are correct.
    This obsessive compulsion to count each COLUMN in each LINE borders on real PARANOIA!

  • How can I configure my computer to another person can use with their own password and do not go through the mine?

    How can I configure my computer to another person can use with their own password and do not go through the mine?

    Hello

    Activate the guest account or setup a new account with the access levels that you must allow.
    either will work.

    How to activate the guest account enabled or disabled in Vista
    http://www.Vistax64.com/tutorials/126933-guest-account-turn-off.html

    How to create a new user account in Vista (also see the related tutorials)
    http://www.Vistax64.com/tutorials/93009-user-account-create.html

    User accounts in Windows Vista
    http://www.optimizingpc.com/Vista/multiple_useraccounts.html

    I hope this helps.

    Rob Brown - Microsoft MVP<- profile="" -="" windows="" expert="" -="" consumer="" :="" bicycle=""><- mark="" twain="" said="" it="">

  • FETCH ONE RECORD IN THE SECOND TABLE OF CORRELATED SUB QUERY

    Hi all

    I have provided the script below, I want to single fecth record in the second table in the join query,

    based on the example below, I want to go get one record of the table emp2 what matches with the emp_id of table emp1, please note emp2 may contain more record for the emp_id emp1 which respects

    all records can be selected in the table emp2.

    DROP TABLE emp1.

    CREATE TABLE emp1 (emp_id NUMBER);

    INSERT INTO emp1 VALUES (1);

    INSERT INTO emp1 VALUES (2);

    COMMIT;

    DROP TABLE emp2.

    CREATE TABLE emp2 (emp_id NUMBER, emp_name VARCHAR2 (100));

    INSERT INTO emp2 VALUES (1, 'Name1');

    INSERT INTO emp2 VALUES (2, 'Name2');

    INSERT INTO emp2 VALUES (1, 'Name3');

    INSERT INTO emp2 VALUES (2, 'Conjoint4');

    COMMIT;

    SELECT * from emp1.

    SELECT * from emp2.

    SELECT T1. EMP_ID, MIN (T2. EMP_NAME)

    FROM EMP1, EMP2 T2 T1

    WHERE T1. EMP_ID = T2. EMP_ID

    GROUP T1. EMP_ID;

    My output should be the same as the result set of query above, but I don't want this logic, please provide the solution by using a different logic, thanks in advance.

    2811876 wrote:

    Thanks for your comments :-)

    My business logic will change to 'Fetch N second timeline table', that's the reason why I asked for a different approach, if I use max, min to achieve this does not allow me to evolve dynamically.

    Although logic has not been expressed at all in your original question, so good job I asked.

    You could do something like:

    SQL > ed
    A written file afiedt.buf

    1 with emp1 (select 1 as the emp_id of union double all the)
    2. Select 2 double
    3               )
    4, emp2 (select 1 as emp_id, 'name 1' as emp_name double union all
    5. Select "name 2' Union double every 2
    6 select 1, 'name' 3' from dual union all
    7. Select 2, 'name 4' double union all.
    8 select 1, 'name 5' from dual union all '.
    9 select 2, 'name 6' from dual '.
    10               )
    11-
    12. end of test data
    13-
    14 select emp_id, emp_name
    15 of)
    16 select t1.emp_id, t2.emp_name
    17, row_number() over (partition by order of t2.emp_name t1.emp_id) rn
    emp1 t1 18
    19 join t2 emp2 (t1.emp_id = t2.emp_id)
    20       )
    21 * where rn<=>
    SQL > /.

    Enter the value for rows_required: 1
    21 Alumni: where rn<=>
    21 news: where rn<=>

    EMP_ID EMP_NA
    ---------- ------
    1 name 1
    2 name 2

    SQL > /.
    Enter the value for rows_required: 2
    21 Alumni: where rn<=>
    21 news: where rn<=>

    EMP_ID EMP_NA
    ---------- ------
    1 name 1
    1 name 3
    2 name 2
    2 name 4

  • Acrobat Professional DC membership on an annual basis with ONE payment per year?

    I would like to subscribe to Acrobat Professional DC on an annual basis with ONE payment per year (same as the creative cloud subscription, I already have) and not on the monthly fee. Is it possible, and where can I find the link to download?

    Thanks for help, I've been browsing for this already too long.

    Hi ReguBee,

    The available option is to Acrobat Pro Dc subscription match monthly Plans and prices | Adobe Acrobat DC. There is no one time annual payment option.

    Kind regards
    Nicos

  • Increase the number of records per page in obiee 10g

    Hello

    can someone tell me how to display multiple records per page in composed fashion, the default value is display as 25 records per page.

    Thanks in advance.

    Chak.

    Hello
    You can reach answres report itself increase line display more thn 25 records per page (it has custom one you can set special report)
    steps: edit answres report you go to your table table properties / pivot--> there is an option called display line by the option of the page here, you can define it.

    medium default setting: this will affect any obiee report.

    If you want more as update the code below into you instantiate config.xml file, after that restart all services of bi.


    1920000
    30
    1000
    64000*.
    25
    64000*.
    75
    64000
    fake


    1920000
    1000
    64000*.
    25
    64000*.
    75
    64000

    http://obieeelegant.blogspot.com/2011/06/exporting-in-Excel-to-download-more.html

    Thank you

    Deva

  • How complete the current year one year Net income in profits not distributed

    We had details in a Dimension of 4 Custom in our new application of IFRS. We call this type of data. Basically we use for detailing the different types of adjustments for IFRS. The problem is the total P & L are copied into the retained earnings for the 4 total of Custom Dimension but not for the descendants of 4 personalized with the exception of [none] members.

    This is the rule:

    "Goal: complete the current year one year Net income in retained earnings"
    KSM erase 'a #L3310 '.
    "KSM Exp ' an L3310 #" & NUNS & "= W #YTD. A LA8999 # "& TOPS"

    What would be the best practice?

    Amendment to the rule on the right side and specified Custom 4 descendants? In this way the Net income will be copied to all members of dimension 4 Custom

    What would happen in the future when we will integrate the business unit in detail in our personal 2? Wouldn't be good practice to change the right side of the rule and put personal descendants 2?

    According to what I saw during the copy of profit form P & L retained we copy only the best members. If bifercation is necessary, then break us into the P & L not profits not distributed.

    I would also advice allows you to copy the top member PKI (place it to the right) ICP None(place it on the left) so what are not disadvantaged as the accounts of PKI, if not retained earnings could not show correct result. This happens for autonomous entities. Since P & L has no intersection of PKI. That the data will not get copied into retained earnings.

    Hope this is useful

    Also, if you find useful or correct answer kindly mark.

    Varun

  • Bought two of the iTouch, one for my wife and one for me. In the Notes his has the "" symbol for the formatting and mine does not work. Any suggestions?

    I bought the iTouch two at a time, one for my wife and one for me. In the application 'Notes' my wife shows the symbol "+" to the formatting and mine does not work. Any suggestion.

    Could you please include screenshots of the so-called issue?

  • Is it possible to record "Mozilla Persona" - password with the FF password manager?

    Is it possible to record "Mozilla Persona" - password with the FF password manager?
    Thank you
    pollti

    Persona.org or login.persona.org is present in your Exceptions list?

  • A user to our small business reports that she one day noticed that the contents of its files to Outlook Express disappeared. Records are intact, but the messages have disappeared.

    Outlook express content of some files went

    A user to our small business reports that she one day noticed that the contents of its files to Outlook Express disappeared.  Records are intact, but the messages have disappeared.  Strangely, what happened to half of its files; the content in the other half is still there.

    She uses Outlook Express 6.
    Suggestions?
    Pamela

    In addition to comments of Bruce, likely OE compacted messages and in doing so, he probably wiped out the where they are absent.  Check your Inbox and message store bak files which are backups dbx files prior to compaction (see www.oehelp.com/OETips.aspx#2).  If you cannot find the bak files, then you will probably use the extract of the service drive of my DBXpress program (see www.oehelp.com/DBXpress/).

    Steve

Maybe you are looking for

  • Link HTML Signature colors

    When I create a HTML signature, all my formatting is licensed, except for the colors, I chose for the links. Example: I have red selected for a link like www.website.com and when I send the email the website link color is blue. (still, no other blue

  • Satellite C855-1TD begins with the message "checking media [Fail].

    My Toshiba laptop has suddenly refused to work well, does not start. When loading from the initial loading of toshiba screen, a black screen will appear saying "Checking media [fail]" I tried everything I saw online that do not opening my laptop. It

  • Save the media?

    OK so my sister sends me pictures of my nephew and my friends send me songs... is there a way I can save these?

  • How can I change the dpi to 600 on a photo?

    I've already saved as a jpg photo, but I'm about to order stickers online. However, the obligation is 600 dpi. I need help to find how to do this. I looked in properties and on the selection of quality under the print menu. Nothing works for me. Help

  • format USB drive

    When I try to format my USB flash drive in win XP it will process any format and then says: windows could not complete the format. When I try to use it it says to format and then it will try again and will say that he was able to complete the format.