SQL statement by using the min aggregate function result extract a line - how?

Need help, try to do something seemingly simple. I'll give a simple example to illustrate the problem.

I'll use a simple table of addresses with 4 fields.

Create the table:
  CREATE TABLE "ADDRESSES" 
   (     "OWNER_NAME" VARCHAR2(20 BYTE), 
     "STREET_NAME" VARCHAR2(20 BYTE), 
     "STREET_NUMBER" NUMBER
   ) ;
complete with 6 rows
Insert into ADDRESSES (OWNER_NAME,STREET_NAME,STREET_NUMBER) values ('FRED','MAIN',1);
Insert into ADDRESSES (OWNER_NAME,STREET_NAME,STREET_NUMBER) values ('JOAN','MAIN',2);
Insert into ADDRESSES (OWNER_NAME,STREET_NAME,STREET_NUMBER) values ('JEAN','MAIN',3);
Insert into ADDRESSES (OWNER_NAME,STREET_NAME,STREET_NUMBER) values ('JACK','ELM',1);
Insert into ADDRESSES (OWNER_NAME,STREET_NAME,STREET_NUMBER) values ('JANE','ELM',2);
Insert into ADDRESSES (OWNER_NAME,STREET_NAME,STREET_NUMBER) values ('JEFF','ELM',3);
We now have this:
Select * from addresses
OWNER_NAME           STREET_NAME          STREET_NUMBER          
-------------------- -------------------- ---------------------- 
FRED                 MAIN                 1                      
JOAN                 MAIN                 2                      
JEAN                 MAIN                 3                      
JACK                 ELM                  1                      
JANE                 ELM                  2                      
JEFF                 ELM                  3                      

6 rows selected
Now, I want to group by street name and obtain a number of houses. At the same time, I would like to know the number of the first and the last House
    select
    street_name,
    count(*) "NBR HOUSES",
    min(street_number) "First Number",
    max(street_number) "Last Number"
     from addresses
    group by street_name

produces

STREET_NAME          NBR HOUSES             First Number           Last Number            
-------------------- ---------------------- ---------------------- ---------------------- 
ELM                  3                      1                      3                      
MAIN                 3                      1                      3                      

2 rows selected
Excellent. Now for the problem. I would also like to list on each line, the owner who lives at number House first and/or the last. It should be noted, assume that the name of the street and the number is unique

It seems I have everything that I need. Don't know how to get home.

I tried:
select
    street_name,
    count(*) "NBR HOUSES",
    min(street_number) "First Number",
    max(street_number) "Last Number",
    (Select b.owner_name from addresses b where b.street_number = min(street_number) and b.owner_name = owner_name) "First Owner"
     from addresses
    group by street_name
But getting a syntax error sql group function unauthorized when I add the subselect statement.

any ideas?

Thanks for any help.

Published by: user6876601 on November 19, 2009 19:08

Published by: user6876601 on November 19, 2009 19:30

Hello

Welcome to the forum!

Get the minimum and maximum number for each street is a pretty simple concept; simpler to describe and simple to code.
Now you want to the owner_name associate the maximum and minimum, which is a concept more complex; a little more difficult to describe and, unfortunately, much less simple to code and much, much more difficult to explain:

select
    street_name,
    count (*)                "NBR HOUSES",
    min (street_number)      "First Number",
    min (owner_name) KEEP (DENSE_RANK FIRST ORDER BY street_number)
                    "First Owner",
    max (street_number)      "Last Number",
    min (owner_name) KEEP (DENSE_RANK LAST ORDER BY street_number)
                    "Last Owner"
     from addresses
    group by street_name
;

You will notice that I used min for "Original owner" and "last owner". Why is this?
The key word in these functions is the FIRST or the LAST word that comes after DENSE_RANK and before ORDER BY. The function at the beginning is simply a break.

In other words, MIN in this context refers only to what needs to happen when there is a link to the first or last in the group. Even if such a thing is impossibe in your data, generic functions must have a mechanism to return a single owner_name when two or more rows have an equal right to having the highest street_number. For example, if we change the address of Joan in 1 hand, then MIN (street_number) is always 1, of course, but who is the person associated with the minimum street_number: Fred or Joan? Both have an equal claim that he owns with the smallest address on Main Street, but aggregate functions must return a single value, so we must have a mechanism to indicate to the system, whether to return 'JOAN' or 'FRED '. In this example, I arbitrarily in the network said een of tie, the lowest name, in alphabetical order, must be returned. In this case, 'FRED' would return, "FRED" prior to "JOAN".

Thank you for including CREATE TABLE and INSERT!

Tags: Database

Similar Questions

  • Why I can't use the nested aggregate function?

    Hello Experts,

    Why I can't use the nested aggregate function? There is not an ora-00979 group by error of expression.

    Oracle Database 11 g Release 11.2.0.4.0 - 64 bit Production

    Select

       SUM (BOX WHEN (KSD_CREATEDATE BETWEEN TRUNC((KSD_CREATEDATE)) AND TRUNC(MIN(KSD_CREATEDATE)) +60) THEN 1  ELSE 0 END) AS col

    DE TABLE_3_4

    GROUP BY STC_FIRMANO

    Thank you

    GROUP BY will manage the SUM function, but the MIN is used incorrectly - use another SELECTION to get it, or work with only with a single line. Otherwise, you could do WITH... get the SUM of SELECT MIN...

  • How to run a SQL statement to use a specific implementation plan

    Hi all

    I have a SQL that has recently been run badly. I tried the Advisor tuning SQL for the given SQL query and it gives the following information:

    GENERAL INFORMATION SECTION

    -------------------------------------------------------------------------------

    Name of the task of tuning: 2q94zb7djr2xn

    The owner task of tuning: LMDBPROD

    Type of work: single SQL statement

    County of execution: 2

    The current run: EXEC_8869

    Type of execution: TUNE SQL

    Scope: COMPLETE

    Time Limit (seconds): 60

    Status: COMPLETED

    Started on the: 03/02/2014-20:43:39

    To the: 03/02/2014 20:44:25

    -------------------------------------------------------------------------------

    Name of the schema: LMDBPROD

    SQL ID: 2q94zb7djr2xn

    SQL text: SELECT NPCOMMON. FGET_ACTION_CODE (ORDNUM) ACTIONCODE, STATUS,

    SUMA COUNT (*) FROM SORDER, WHERE HEADORDNUM IS NOT NULL AND

    NPCOMMON. FGET_PRODUCTOFFER4ORDER (ORDNUM) IN (SELECT ID FROM)

    PRODUCTOFFER WHERE PPSPECIFICATION_ID IN (SELECT ID FROM)

    PPSPECIFICATION WHERE PCLASS_CODE IN (SELECT PCLASS_CODE FROM)

    ARUSERGROUP WHERE CODE IN (SELECT ARUSERGROUP_CODE FROM)

    ARUSER_ARUSERGROUP WHERE ARUSER_USERNAME =: B1 AND STATUS = '1')

    AND STATUS = '1'))) GROUP BY NPCOMMON. FGET_ACTION_CODE (ORDNUM),

    STATUS

    -------------------------------------------------------------------------------

    RESULTS SECTION (1 result)

    -------------------------------------------------------------------------------

    1-alternative Plan conclusion

    ---------------------------

    Some implementation plans alternative for this statement was found by searching

    performance data in real-time and historical of the system.

    The following table lists these plans sorted by their average time.

    See "SECTION of ALTERNATIVE PLANS" section for detailed information on each

    plan.

    plan ID hash last visit elapsed note of origin (s)

    -- ---------- -------------------- ------------ --------------- ----------------

    1 617797893 2013-07-11/07: 45:20 9.555 no reproducible STS

    2 1311086720 2014-01-31/04: 00:44 19.569 AWR

    3 1226863820 2014-01-31/18: 00:24 AWR 21.158

    4 1359606848 2014-02-03/16: 00:34 21.492 AWR original plan

    The plan with hash 617797893 seems the most efficient one and is based on some specific SQL Tuning Set I ran on this time. But the note says that the plan is not reproducible. Is there anyway how can I force the SQL statement to execute the plan? The database version is Standard Edition 11.2.0.1.0

    Best regards

    Rodriguez

    Hello

    I think you can use this

    http://rnm1978.WordPress.com/2011/06/28/Oracle-11g-how-to-force-a-sql_id-to-use-a-plan_hash_value-using-SQL-baselines/

    before 11 g, we used to create an outline stored for this.

    concerning

  • How not to use the squint no functionality?

    I forgot how not to use the squint no functionality. Can anyone help?

    18.0 Firefox was released last Tuesday, you need to update.

    See if this FAQ for NoSquint answers your questions.

    https://urandom.ca/NoSquint/#FAQ

  • How to use the Print Screen function?

    I've seen various descriptions of how to use the print screen function.

    It would be nice to actually tell one that works.  None have worked for me.

    [Fn] and Prt SCr does not work.

    CTRL and Prt SCr does not work.

    CTRL, Alt, and Prt SCr does not work.

    [Fn], Ctrl and Prt SCr does not work.

    If anyone knows the correct method to activate the screen capture function which would be a good thing.

    From the looks of things, HP has a big problem with this function.

    Here's a microsoft articleon the use of the screenshot function.

    This should answer your questions.

    Thanks for taking a peek.

  • IM 10 atm installation initiated Preview and I want to know: is it easy to use the dual-boot functionality, if I have 2 hard drives

    Hello!

    IM 10 atm installation initiated Preview and I want to know: is it easy to use the dual-boot functionality, if I have 2 hard drives? I have win7 on my main drive (SSD) and I want to install 10 preview initiated a new partition on my 500 GB hard drive, I created. I'll have to change smth in the bios menu, or I will be asked to choose between win7 and win10 in a menu after boot?

    Yes, it's, it's just like installing Windows on another partition.

    To learn more:

    http://answers.Microsoft.com/en-us/Insider/wiki/insider_wintp-insider_install/how-to-dual-boot-the-latest-Windows-build-with/9695dfc7-1C13-4D8D-B10B-587e78c6ac36

  • Can I use the mini HDMI port to safely load my HX200V?

    I used the mini HDMI port to load my camera HX200V battery,

    but the battery does not very long load, even after being recharged.

    I have hurt the battery?

    Hi RickS8082,

  • Problem opening pdf files.  I have Acrobat Reader DC/Windows by default, but when I click on the file, a file conversion screen with all these codes. Must use the "open with" function which is a nuisance.  Why it will not default?

    Problem opening pdf files.  I have Acrobat DC/Windows by default, but when I click on the file, a file conversion screen now with all these language codes. Must use the "open with" function which is a nuisance.

    Why it will not open by default when I click on the file?

    Hello

    I guess that you are looking for this:

    Open drive

    Go in Edition > Preferences > General

    Uncheck the option, the online storage see the opening of the files

    Click OK and restart

    Thank you

    Abhishek

  • I used the text tool function more than the reminder function, how do I get it back?

    I used the text tool function more than the reminder function, how do I get it back?

    Hi Slate7Berta,

    Please use Adobe acrobat reader DC Acrobat Reader DC Learn & support instead of touch Adobe, there seems to be a compatibility issue.

    Kind regards

    Nicos

  • I'm unable to use the Live View function when working with JavaScript in Dreamweaver.

    I'm currently trying to set up my own Web site with dreamweaver and am very familiar with the languages Java and JavaScript. However, whenever I try to use the Live View function it never let me. In addition, I can't get a preview of my work in a browser, as to do so is greyed out.

    However, I noticed that when using html in a project, all these functions are available. Any ideas how I can be able to use these features?

    Or perhaps you mean a .jsp file that is a Java Server Page.

    Modern web pages are almost entirely HTML code with CSS for styles and JavaScript for functionality added as games & slideshows or interactive menus.  It does not seem possible for me that you have been creating web pages entirely with JavaScript.

    Nancy O.

  • list of sql-operators, who use the database indexes.

    Give a list of the sql operators, who use the database indexes.

    I'm interested to know if ' group by '-operator uses indexes.

    why it has not been used here?

    because there is no general rule to that: as stated it depends on table and index layout if the optimizer decides to go to index or not.

  • How to use the xp20 extension functions?

    Hello everyone,

    I want to use Java (JAXP) to perform XSL transformations using the xp20 extension functions (http://www.oracle.com/XSL/Transform/java/oracle.tip.pc.services.functions.Xpath20).

    Transformation of"basic" is at work,
    Seller: < xsl: value - of select = "system-property('xsl:vendor')" / >
    Version: < xsl: value - of select = "system-property('xsl:version')" / >

    results in:
    Vendor: Oracle Corporation.
    Version: 2

    However, when I try < xsl: value - of select = "xp20:current - dateTime ()" / > (Yes, the namespace is declared), I get the following error:
    XML-22043: Fehler (error) bei Erweiterungsfunktion: method 'current-dateTime"non found
    (roughly: Error (error) according to the extension: "current-dateTime" method not found)

    This is after you have added the bpm - services.jar to my classpath. Before, I had a "class not found" (or something like that...).

    Assume that something is missing in my classpath - can I anyone tell me who I need to add the jar files and where to find them? This should be compatible with the suite and JDeveloper 10.1.3.4 SOA 10.1.3.4

    Thank you very much

    Finch

    4526876 October 9, 2006 bpm - services.jar (of soa_windows_x86_bpel_101310.zip)

    1211311 xmlparserv2.jar (from oracle xdk - 10.2.0.2.0)

    Don't run with all the exits, no variable set CLASSPATH, no ORACLE_ * defined variables:

    % java -cp "xmlparserv2.jar;bpm-services.jar" oracle.xml.parser.v2.oraxsl -w -v -debug -l input.xml -s date.xsl -r out
    Release version: Oracle XML Developers Kit 10.2.0.2.0 - Production
    1 XML document will be transformed using XSLT stylesheet specified in date.xsl with 1 thread
    Parsing file date.xsl
    Parsing file input.xml
    Transforming XML document specified in input.xml
    

    It seems to be a classpath issue. Try with java-verbose and you should see a line like

    ...
    [Loaded oracle.tip.pc.services.functions.Xpath20 from file://path/to/bpm-services.jar]
    ...
    
  • Hide using the date of beginning and end of line

    Is there a way to hide using the start date and end date of line

    One way to do is to add a filter column (which may hide once it is configured) like this:

    The formula in D2, filled to the bottom, is:

    = AND(A2≥$B$8,A2≤$B$9)

    The filter (on column D) looks like this in the right panel:

    C9 formula is:

    = SUMIFS(C,A,">="&B8,A,"<="&B9)

    After changing the end date of 2014-12-31, you get this:

    I left column displayed D just for illustration.

    SG

  • I'm unable to use the email as my iMap password is incorrect - how to reset?

    I'm unable to use the email as my iMap password is incorrect - how to reset?

    You need to reset your password to email through the email provider. It is not a specific device parameter. Your password is related to your e-mail account. Seek help from your email for this provider.

  • I use the g5 U800 mobile.i need to know how to connect to internet from my mobile to pc.

    mobile g5 Internet connection for pc

    I use the g5 U800 mobile.i need to know how to connect to internet from my mobile to pc
    Hello
     
    You must have GPRS activated from your network service provider.

    To connect the phone to the computer, you need a PC suite installed on the computer. If the phone manufacturers have supplied PC suite CD, then install the software on the computer.
    The operating system on the computer and the mobile phone are different, so communication is not directly.  PC suite software acts as a mediator between the computer and the phone and helps to establish effective communication between the phone and the computer. If the CD is not provided, then look for in PC suite online and download it.
     
    Thank you

Maybe you are looking for