Select Non-Aggregated Field in a Query

Good morning,
This should be easy but I can't figure it out.
You have a table with three fields; Salesperson, Quarter, Sales(value)
Build a query that outputs the best sales quarter for each salesperson (i.e. Max(Sales), Group by Salesperson) that includes the quarter.  I don't want to group by the quarter because I just get the whole list.
Advice please,
Tom.

Tom,
Check this?
declare @tab table(id int identity,salesperson varchar(100),quarter int,sales int)
insert @tab(salesperson,quarter,sales) select 'jk',1,100
insert @tab(salesperson,quarter,sales) select 'jk',2,300
insert @tab(salesperson,quarter,sales) select 'jk',3,200
insert @tab(salesperson,quarter,sales) select 'jk',4,50
insert @tab(salesperson,quarter,sales) select 'jay',1,505
insert @tab(salesperson,quarter,sales) select 'jay',2,0
insert @tab(salesperson,quarter,sales) select 'jay',3,505
insert @tab(salesperson,quarter,sales) select 'jay',4,244
;with cte
as
select id,salesperson,quarter,sales,row_number() over(partition by salesperson order by sales desc) rn
from @tab
select id,salesperson,quarter,sales
from cte
where rn=1
The above will generate only one row in case of 'jay' record even though he has TWO quarters with the highest value. If you need both rows to be generated, then use DENSE_RANK() in place of ROW_NUMBER aggregate function as below:
declare @tab table(id int identity,salesperson varchar(100),quarter int,sales int)
insert @tab(salesperson,quarter,sales) select 'jk',1,100
insert @tab(salesperson,quarter,sales) select 'jk',2,300
insert @tab(salesperson,quarter,sales) select 'jk',3,200
insert @tab(salesperson,quarter,sales) select 'jk',4,50
insert @tab(salesperson,quarter,sales) select 'jay',1,505
insert @tab(salesperson,quarter,sales) select 'jay',2,0
insert @tab(salesperson,quarter,sales) select 'jay',3,505
insert @tab(salesperson,quarter,sales) select 'jay',4,244
;with cte
as
select id,salesperson,quarter,sales,dense_rank() over(partition by salesperson order by sales desc) rn
from @tab
select id,salesperson,quarter,sales
from cte
where rn=1
Thanks,
Jay
<If the post was helpful mark as 'Helpful' and if the post answered your query, mark as 'Answered'>
Yep
thats true
you can use RANK also instead of DENSE RANK as in this case you're looking for the highest
Please Mark This As Answer if it helps to solve the issue Visakh ---------------------------- http://visakhm.blogspot.com/ https://www.facebook.com/VmBlogs

Similar Messages

  • -- SQL -- GROUP BY clause: non-aggregate fields mandate

    Hello,
    I was studying Databases, (particularly the retrieval of the data), and found something interesting.
    While using an Aggregate Function in the SELECT clause, it is mandatory to have all the non-aggregate fields in the SELECT clause to be there in the GROUP BY clause.
    For example,
    SELECT dept_no, SUM(salary)
    FROM employee
    GROUP BY dept_no;
    The above SQL works fine.
    But, what if the user misses the dept_no in the GROUP BY clause or he/she misses the GROUP BY clause itself?
    Certainly, it is an error.
    Why is this error not handled by the database. I mean, the database should be smart/intelligent enough to add the GROUP BY clause by itself. So suppose, if I miss out the GROUP BY clause or miss a non-aggregate field from the SELECT clause when I am having at least one aggregate function on a field with at least one non-aggregated field in the SELECT clause, the database should check the GROUP BY clause at time of compilation and add the mandate missed out fields in the GROUP BY clause.
    Example,
    SQL1:_
    SELECT dept_no, SUM(salary)
    FROM employee
    GROUP BY dept_no;
    SQL2:_
    SELECT dept_no, SUM(salary)
    FROM employee;
    Here, the SQL1 and SQL2, both should give me same outputs without an error.
    I am unable to understand why is this not handled?

    Hi,
    998478 wrote:
    ... If we mix aggregate and non-aggregate values then there must be a GROUP BY clause containing all the non-aggregate values. Why is this not handled by the database/compiler itself? It IS handled by the compiler itself. The compiler handles it by raising an error. The compiler has no way of knowing whether you want to remove something from the SELECT clause, or to add something to the GROUP BY clause, or not to use aggregate functions, or to use more aggregate functions, or some combination of the above. If the compiler re-wrote your code, and did any of these things automatically, it would be wrong more often than it was right, and you would (rightly) be complaining about its behavior.
    For example, this is clearly wrong:
    SELECT    deptno
    ,       job
    ,       SUM (sal)
    FROM       scott.emp
    GROUP BY  deptno
    ;What is the right way to fix it?
    <h3>1. Remove something from the SELECT clause</h3>
    SELECT    deptno
    ,       SUM (sal)
    FROM       scott.emp
    GROUP BY  deptno
    ;<h3>2. Add something to the GROUP BY clause</h3>
    SELECT    deptno
    ,       job
    ,       SUM (sal)
    FROM       scott.emp
    GROUP BY  deptno
    ,         job
    ;<h3>3. Not use aggregate functions</h3>
    SELECT    deptno
    ,       job
    ,       sal
    FROM       scott.emp
    ;<h3>4. Use more aggregate functions</h3>
    SELECT    deptno
    ,       MIN (job)
    ,       SUM (sal)
    FROM       scott.emp
    GROUP BY  deptno
    ;These aren't all the options, either. For example, the correct fix might be to use analytic functions instead of aggregate functions.
    How can anybody say which of these is right? All of them are the right answer for some problem.
    By the way, saying that everying in the SELECT clause must be an aggregate or in the GROUP BY clause is a bit over-simplified.
    More completely, here are the ABC's of GROUP BY:
    When you use a GROUP BY clause and/or an aggregate function, then everything in the SELECT clause must be:
    (A) an <b>A</b>ggregate function,
    (B) one of the "group <b>B</b>y" expressions,
    (C) a <b>C</b>onstant, or
    (D) something that <b>D</b>epends entirely on the above. (For example, if you "GROUP BY TRUNC(dt)", you can SELECT "TO_CHAR (TRUNC(dt), 'Mon-DD')").
    Edited by: Frank Kulash on Apr 13, 2013 1:44 PM
    Added code examples.

  • Alignment and restriction of Custom field in SAP query report

    Hi Experts,
    I have one custom field in query report(SQ01) called Amount in local currency which is calculated based on Amount in document currecy * exchange rate.
    But this field values are coming in left alignment instead of right alignment so how i should get in right alignment and second issue is how i can restrict field value to only 2 decimals.
    I tried the below link "http://media.techtarget.com/searchSAP/downloads/SAP_Query_C7.pdf" but the steps they mentioned are not appearing in SQ01 for example in that link they mentioned to click Basic List option for advanced steps but when i click i goes directly to field list with field groups on left pane
    Please provide solution for this.
    Thanks&Regards,
    narasimha

    Hello narasimha,
    In the Infoset when you create the additional field, enter an existing SAP table field that has type CURR in the parameter labeled LIKE Reference.  For example you can enter BSAK-DMBTR as a value. When you select the additional field in the query, the currency will also show.
    Kind Regards,
    Rae Ellen Woytowiez
    Edited by: Rae Ellen Woytowiez on Apr 25, 2011 11:27 PM

  • How to separate non metric fields in Fact tables

    Hi All,
       I am having metric fields along with some non metric fields  in fact tables(All the fields has to be present in fact table only). Is it possible to group all non aggregated fields and aggregated fields in the same fact tables. Please advise.
    regards,
    Guru

    check this
    OBIEE, Endeca and ODI: Fact and Dimension from single source Table
    Thanks,
    Saichand

  • Problems with query on a non-database field

    Hi,
    Hopefully I am in the correct section...
    I have some problems. I wanna query a non-database field but it does not work for one of them. I have tried the following...
    declare
    vsNewDefaultWhere varchar2(4000);
    vbFirstWhere boolean;
    cursor curArea is
    select a1_area, a1_hbno, a1_seqno
    from b1_in, c1_hdr, a1_bl
    where b1_sequenceno = a1_seqno
    and b1_shipid = a1_hbno
    and b1_id = :c1_shipid;
    rowArea curArea%ROWTYPE;
    procedure mergeStrings (sNewWhereClause varchar2) is
    begin
    if not vbFirstWhere then
    vsNewDefaultWhere := vsNewDefaultWhere || ' and ';
    end if;
    vsNewDefaultWhere := vsNewDefaultWhere || sNewWhereClause;
    vbFirstWhere := false;
    end mergeStrings;
    begin
    navigate.resetselrows('IMP_HDR');
    navigate.resetselrows('IMP_DTL');
    if not navigate.customwhereclause then
    navigate.resetwhereclause('IMP_HDR');
    end if;
    vsNewDefaultWhere := Get_Block_Property('IMP_HDR', DEFAULT_WHERE);
    vbFirstWhere := vsNewDefaultWhere is null;
    ---- does work!
    if :IMP_HDR.c1_usecode is not null then
    mergeStrings('c1_shipid in (select b1_id from b1_in where b1_fac = ''' || :global.fac || ''' and b1_comp = ''' || :global.comp || ''' and b1_code like ''' || :c1_usecode || ''')');
    end if;
    ---- does not work!
    open curArea;
    fetch curArea into rowArea;
    if curArea%found then
    if :IMP_HDR.c1_area is not null then
    mergeStrings('c1_shipid in (select b1_id from b1_in, c1_hdr, a1_bl where b1_fac = ''' || :global.fac || ''' and b1_comp = ''' || :global.comp || ''' and b1_sequenceno = ''' || rowArea.a1_seqno || ''' and b1_shipid = ''' || rowArea.a1_hbno || ''' and rowArea.a1_area like ''' || :c1_area || ''')');
    end if;
    end if;
    end;
    Thanks for your help in advance and let me know if you Need more Information.

    Hello,
    Ask Personalization questions in the dedicated E-Business Suite forum ;-)
    Francois

  • How to display records from a query into non-database field

    Hi
    I a have a problem:
    I have a query with many tables and 6 column(select a,b,c,d,e,f from x,y,z,t,s,g where conditions) and I use 3 parameters.
    I create 3 parameters :datai,:dataf and :partener and a button with a trigger when button is pressed.
    Then a create a manualy block with six field non-database a1,b1,c1,d1,e1,f1.
    Now I want to display all the records from my query into a1,b1,c1,d1,e1,f1 where a1=a,b1=b,etc. and all the records (if I have 20 record, it will display 20 records in non-database field) when I press the button.
    How I made:
    I create a cursor with query then
    begin open cursor
    loop
    fetch cursor into :a1,:b1,:c1,:d1,:e1,:f1;
    end loop;
    close cursor;
    end;
    It display one record in a1,b1,c1 only and it have to display 100 records and are date for all the fields.
    Can somebody help me in this problem?
    Thanks.
    Edited by: 928437 on Oct 1, 2012 2:55 AM

    Creating a view, and querying that into a database block is an excellent solution.
    To use the non-database block:
    You're missing the all-important Next_Record; command.
    <pre> Begin
    Go_block('X'); -- block X is the non-database block
    Clear_Block(No_Validate);
    open cursor X1;
    loop
    If :System.Record_status != 'NEW' then
    Next_Record;
    End if;
    fetch X1 into :a1,:b1,:c1,:d1,:e1,:f1;
    Exit when X1%NOTFOUND;
    end loop;
    close X1;
    end;</pre>

  • Addition of checkbox and 2 fields in ABap query selection screen

    Hi
    I need to add chack boxes and 2 fields in ABAP query which is using LDB QMI. can u pls let me know how to do that.

    Hi Tarun,
    I am still not clear with the problem..I guess you require plant in your selection screen which you have.
    i guess if you go to sq01tcode there is a option infoset query from where you can give your selection options and value.
    have you selected all the fields in infoset and made a selection screen?
    When you have done with your infoset you just need to diplay the fields and there is a automatic program generated.
    Let me know...
    Regards,
    Nihkil.

  • I need use conditions in the select fields of a query.

    Hello,
    Is possible, that I can have conditions in the select fields of a query? In a invoice when the type is cancellation I want to put *-1 to price and if is other type the price is normally.
    If VBRK.FKART = 'S1' THEN KWERT*-1 else KWERT .
    Thank you very much.

    you can do two things:
    1. select the data into internal table and loop through the internal table and do the necessary changes
    SELECT fkart kwert
    FROM vbrk
    INTO TABLE itab
    WHERE ...
    LOOP AT itab.
    IF itab-fkart EQ 'S1'.
    itab-kwert = itab-kwert * -1 .
    MODIFY itab.
    ENDIF.
    ENDLOOP.
    2. use select-endselect and change the data acc. to your needs inbetween and append the internal table.
    SELECT fkart kwert
    FROM vbrk
    INTO wa
    WHERE ...
    IF wa-fkart EQ 'S1'.
    wa-kwert = wa-kwert * -1 .
    ENDIF.
    APPEND wa TO itab.
    ENDSELECT.
    (The first approach is probably faster.)

  • Order of the selection fields in SAP QUERY

    Hello All,
    How can we set the order of the selection fields in SAP QUERY!
    Regards!
    Ashish

    Hi,
    You can go into infoset and change the order.
    Or you can select 1 by 1 in the same order, you want to display.
    Below is the link which might help you:
    help.sap.com/printdocu/core/Print46c/EN/data/.../BCSRVQUE.pdf
    Please revert, if needed more clarifications
    Regards,
    Yashwin

  • Missing field for MDX query for All Members

    Hello,
    I'm using MDX query with SSRS for report and I ran into this issue:
    Query 1:
    select non empty ([Product].[Category].allmembers*[Date].[Calendar].[Calendar Year].allmembers ) on 1,
    ([Measures].[Internet Sales Amount]) on 0
    from [Adventure Works]
    go
    Query 2
    select non empty ([Product].[Category].[All]*[Date].[Calendar].[Calendar Year].allmembers ) on 1,
    ([Measures].[Internet Sales Amount]) on 0
    from [Adventure Works]
    In case I run query 2 in SSDT (query designer), it doesn't return first column whereas if I run above two queries in SSMS, I get similar columns/fields.
    How it can be resolved in SSRS to return all columns for query 1 and 2.
    Thanks,
    P
    mark it as answer if it answered your question :)

    Hello,
    I'm using MDX query with SSRS for report and I ran into this issue:
    Query 1:
    select non empty ([Product].[Category].allmembers*[Date].[Calendar].[Calendar Year].allmembers ) on 1,
    ([Measures].[Internet Sales Amount]) on 0
    from [Adventure Works]
    go
    Query 2
    select non empty ([Product].[Category].[All]*[Date].[Calendar].[Calendar Year].allmembers ) on 1,
    ([Measures].[Internet Sales Amount]) on 0
    from [Adventure Works]
    In case I run query 2 in SSDT (query designer), it doesn't return first column whereas if I run above two queries in SSMS, I get similar columns/fields.
    How it can be resolved in SSRS to return all columns for query 1 and 2.
    Thanks,
    P

  • Sorting on non database fields

    Hi,
    I have a Master-Detail form ( query only form). The detail block has 10 DB fields and 2 NON DB fields (check boxes) . I have implemented Sorting functionality in such a way that, I have buttons on the top of each field and if the button is pressed on , let us say for Eg. Emp Name, sorting should be done on Emp Name and followed by other fields.
    Order by clause after pressing Emp Name looks as follows:
    Order by empname, empno, sal,......
    But can we implement the sorting functionality for check boxes also ? ( Check boxes are non DB Fields )
    These check boxes are populated with cursor in POST-QUERY trigger at block level ( check boxes are in Detail block.)
    how to implement soring on these two check boxes?
    Cheers
    Ram Kanala

    Thanks Every one,
    We can have 2 approaches:
    1. Since my block is based on the view, i have to change my view, to include
    the Non- DB check box values. I can get the check box values using a function.
    2. Another approach is , write a SELECT statement to select all the
    coumns from the view along with the two NON-DB fields, (using function )
    and use this SELECT clause in the QUERY SOURCE property of the block.
    Thanks a lot for your help.
    Cheers
    Ram Kanala

  • When we change the non-mandatory field in the form, it doesn't get updated

    Hi... I have one question here..
    If I have non-mandatory fields in a custom form, and when I query the form and change the value in the non-mandatory field and click on save, then it doesn't save. It says 'No Changes to Save'. But, it's not the same for non-mandatory fields.
    Can you please suggest me?
    -vrdida

    VRdida,
    If I understand correctly, you have a non-Required item in your form that has an LOV assigned. While this item is Required=No, it works correctly. When you change the Required property of the item to 'Yes' then it fails. When this occurs, do you get an error message? Are you able to select a value from the LOV?
    It sounds like the Required=Yes property might be preventing you f rom opening the LOV. Try setting the Module property: Defer Required Enforcement = Yes. This is the typical setting in an EBS form. This is what allows you to navigate out of a Required field if the value is NULL, but will give you a Required message when you attempt to save the record if the value is still NULL.
    Hope this helps,
    Craig B-)
    If someone's response is helpful or correct, please mark it accordingly.
    Edited by: CraigB on Apr 6, 2011 11:43 AM

  • Xml file, non database field etc..

    Hi,
    There is a requirement for putting a non database field in an
    infobus grid control and populating it with some value at the
    runtime. As this is not directly available in gridcontrol, many
    have tried using a join query as I could see from the
    postings.(Like select deptcode,desc from emp, dept where
    emp.deptcode = dept.deptcode). This works well when the data is
    queried from the database. But when a new deptcode is entered, it
    is not possible to get the corrosponding value from the database
    and show it on this field, as u get readonly attribute error.
    Even if u explicitly change the attribute to updateable the error
    will remain as such.
    The cause of this problem, I have tracked down to the xml file.
    The entity for the updateable table (in this case EMP) does not
    have the attribute for deptdesc. If this is manually added, it is
    possible to add values to the deptdesc column. The catch is when
    inserting a row to the database. All the attributes in the
    entity
    will appear in the insert statement and u end up with an invalid
    column name error for the deptdesc column.
    Seeing this consistant behaviour, I assume that the insert
    statement is created by parsing the xml file. Had there been an
    attribute value in the xml file for insert into database (just
    like IsNotNull etc.. perhaps IsUpdateable which can be set
    manually), while parsing this attribute can be removed.
    To do this I would like to know where this xml parser is
    implemented in jdev. Is it possible for me to change its
    behaviour or can I expect to get a patch for this? This
    functionaliy is very much essential for me, as I am in the middle
    of a very large project using jdev2.0. I don't mind implementing
    it, if the source is available.
    Any helpful suggestions, comments are welcome. Sorry for the long
    post and thanks
    --Gopal
    null

    I don't think it will work with a non-db-item. But you could create a separate block based on your image_tb-table, use read_image_file on the then db-based-column and then simpy issue a commit_form.

  • Display value in custom field selection of standard field

    Hi,
    I want to display the country value based on the Account selection, that is the country associated with the selected Account.
    I created Contact extension BO and added country field with data type CountryCode. Account is a standard field.
    I am able to fetch country value but assigning the value to Country field can be done in only BeforeSave.absl
    I have also provided validation for this country field.
    Issue here is:
    First Validation-OnSave.absl gets called and then BeforeSave.absl.
    I want the country value to be displayed once the user selects Account.
    Regards,
    Vijaya Chavan

    Hi Vinod,
    I got the issue.
    AfterModify.absl gets called when the Contact Quick Create screen gets loaded and not after selecting the Account field value.
    So I tried geting the value directly from the following path without firing a query in BeforeSave.absl.
    this.CurrentDefaultIsContactPersonFor.BusinessPartnerRelationship.FirstBusinessPartner.AddressInformation.GetFirst().AddressSnapshot.PostalAddress.GetFirst().CountryCode;
    But BeforeSave.absl gets called when I click on "Save". I wanted the value to be displayed soon after the Account Value is selected.
    Regards,
    Vijaya Chavan

  • Creation of local field in ABAP Query

    Hi
    Please let me know how to create a local field in ABAP query. I am finding the option inactive in SQ01.
    Regards
    Priyadarshini

    hi priya,
         *__Adding u201CLocal Fieldu201D (user defined field) in SAP Query_ :
    There is also facility to add the user defined fields in SAP query output. Also we can provide calculation formula for calculating values for this user defined field.
    Calculation formula consists of standard fields from standard SAP tables. So the values fetched for particular standard SAP fields from standard SAP tables get calculated as per the calculation formula defined for the user defined field and displays the value accordingly.
    To do this first go to change mode for Query which automatically takes you to screen shown below and click on icon   , as below :
    Then further screen will appears. So select the Field group and again click on the same icon button   .
    Then switch on the Short names for the fields and give the short names to fields which we need to use in Calculation formula.
    Give the short names and then created u201CLocal Fieldu201D, as shown in below screen shot. Also Short names are given to fields, which can be used further for calculation.
    Defining Local Field u201CREM_QTYu201D along with its field type and Calculation formula.
      In this case we have 
      defined field type for new  
      field as similar to
      ORD_QTY and
      Calculation formula is  
      defined.
    Also its possible to have Conditional logic for Local field by putting Condition in u201CConditionu201D line.
    Now activate this newly added Local field for coming it in output screen. To do the same again go to u201CBasic Listu201D and activate the Local Field as shown below :
    i think this will help u
    regards,
    sindhu.

Maybe you are looking for