Group By Statement

Hello, I am new to SQL so I apologise. I need to execute the following query on my Oracle 10g database:
I have a table like this:
OID             Truck    Loading Time        Timestamp
1 HT01 10 10:01
2 HT02 8 09:03
4 HT02 6 10:04
5 HT01 10 11:01
8 HT01 10 13:00
9 HT01 20 15:00
I need to create a query that will show me the average Loading Time for the last 2 database entries for each machine. (i.e. this would be the avg of OID 8 and OID 9 for HT01)
Truck Loading Time
HT01     15
HT02     7
I have tried:
select Truck, avg(loading time) from TABLE where rownum > 3 group by Truck * ....takes minutes to run*
Are there alternatives>?

I'd do this by doing:
select truck, avg(loading_time)
from   (select sd.*,
               row_number() over (partition by truck order by oid desc) rn
        from   sample_data sd)
where  rn <= 2
group by truck;Of course, since you have to order the whole set of data first, the larger your dataset, the longer it's going to take. At least this way, you'll get the right results!
Edited by: Boneist on 27-Jul-2011 09:27
Waaaay too slow!

Similar Messages

  • How to create a Module Component containing a MAX().. GROUP BY Statement

    Hi
    What do I have to do, to get a module component, which, in the end, returns a statement like
    SELECT mas_id, mas_name
    FROM v_masken_zugriff
    WHERE mzu_datenbank = 'database'
    AND (UPPER(vur_name) = UPPER(user)
    OR UPPER(vur_name) IN (SELECT granted_role
    FROM dba_role_privs
    WHERE UPPER(grantee) =UPPER( user)
    GROUP BY mas_id, mas_name
    i.e. how do I generate a GROUP BY Statement?
    Thanks a lot!
    Karine

    Where are you trying to place this?
    Is this a LOV or a pl/sql?

  • GROUP BY statement problem due to a version update

    Hello:
    Recently, I updated B.Objects XI R2 from SP2 to SP5 and I stumbled with some problems. The biggest one is that the SQL View inside SQL Editor doesn't show GROUP BY statement when Autogenerated SQL radio button is activated. For example:
    SELECT
    VMINROAQ_VMOCMTDQ.OCMT_DS_OPERADOR_CMT,
    VMSIQ9.VMINROAQ.OCMT_CO_OPERADOR_CMT,
    VMSIQ9.VMINROAQ.PRES_NU_PRESEL_P5,
    VMSIQ9.VMINROAQ.FECH_NU_ANNO,
    VMSIQ9.VMINROAQ.FECH_NU_MES,
    VMSIQ9.VMINROAQ.INRO_CA_LINEAS_RECLAMADAS,
    VMSIQ9.VMFECHDQ.FECH_NO_MES,
    VMSIQ9.VMINROAQ.INRO_CA_TIEMPO_MEDIO_RESOL
    FROM
    VMSIQ9.VMINROAQ,
    VMSIQ9.VMOCMTDQ  VMINROAQ_VMOCMTDQ,
    VMSIQ9.VMFECHDQ
    WHERE
    ( VMSIQ9.VMINROAQ.OCMT_CO_OPERADOR_CMT=VMINROAQ_VMOCMTDQ.OCMT_CO_OPERADOR_CMT  )
    AND  ( VMSIQ9.VMINROAQ.FECH_NU_MES=VMSIQ9.VMFECHDQ.FECH_NU_MES and VMSIQ9.VMINROAQ.FECH_NU_ANNO=VMSIQ9.VMFECHDQ.FECH_NU_ANNO  )
    AND
    VMSIQ9.VMFECHDQ.FECH_NO_MES  =  'Diciembre'
    AND
    VMSIQ9.VMINROAQ.FECH_NU_ANNO  =  2009
    *GROUP BY VMINROAQ_VMOCMTDQ.OCMT_DS_OPERADOR_CMT,*
    VMSIQ9.VMINROAQ.OCMT_CO_OPERADOR_CMT,
    VMSIQ9.VMINROAQ.PRES_NU_PRESEL_P5,
    VMSIQ9.VMINROAQ.FECH_NU_ANNO,
    VMSIQ9.VMINROAQ.FECH_NU_MES,
    VMSIQ9.VMINROAQ.INRO_CA_LINEAS_RECLAMADAS,
    VMSIQ9.VMFECHDQ.FECH_NO_MES,
    +VMSIQ9.VMINROAQ.INRO_CA_TIEMPO_MEDIO_RESOL+
    (Bold words only appear in SP2, not in SP5.)
    With this problem I have incongruities in my new reports, but it's odd that reports made with SP2 maintain the same old structure with SP5.
    A solution is to check "personalize SQL" radio button, but I can't use it because my client demands it. So, does anyone know why B.O. does this? Even more, does anyone know a trick or a way to solve this problem?
    I hope your news. Kind regards.
    José María.

    Hi,
    Is this problem for only one report or no.of reports. If it is for a no. of reports  then the universe on which these reports are bulid i.e in universe parameters -> options (last tab) -> there some parameters related to grouby clause
    Try to enable them and check it reporting level.
    Cheers,
    Suresh Aluri.

  • Any hints on what may be wrong with this GROUP BY statement?

    Hi,
    I am testing the code below suggested on this site. When I tried it code and during my CHECK, and it gets to the GROUP BY line, and jumps back to the SELECT statement with the following message (even though DATE2 is in the GROUP BY statement):
    E:The field "/BIC/AODSSSS00~DATE2" from the SELECT list is is
    missing in the GROUP BY clause. is missing in the GROUP BY clause. Is
    missing in the GROUP BY clause. is missing in the GROUP BY clause. is
    I have played around, changing DATE2 in the GROUP By line with /BIC/AODSSSS00~DATE2 or /BIC/AODSSSS00-DATE2 or /BIC/DATE2, but still I get likewise.
    loop at RESULT_PACKAGE into wa_RESULT_PACKAGE.
    SELECT NUM ITEM /BIC/DATE1 DATE2 sum( QTY ) as QTY
    INTO corresponding fields of table it_TABLE1
    FROM /BIC/AODSSSS00
    where /BIC/DATE1 <= wa_RESULT_PACKAGE-DATE2
    AND NUM = wa_RESULT_PACKAGE-NUM
    AND ITEM = wa_RESULT_PACKAGE-ITEM
    GROUP BY NUM ITEM /BIC/DATE1 DATE2.
    wa_RESULT_PACKAGE-/BIC/AONTIMQTY = sum.
    MODIFY RESULT_PACKAGE from wa_RESULT_PACKAGE.
    Endloop.
    Thanks

    I am not totally clear on what you want to achieve.  But please look this code over and see if it is closer to what you want to do.
    I changed your workarea to a field-symbol, which are a little more convenient to use.  <result_fields> is already defined for you in your end routine.
    I used tables and fields that exist in our system, but you should be able to translate those back to your system.
    Please let me know if you need more help.
    LOOP AT result_package ASSIGNING <result_fields>.
      SELECT me_order_n me_itemno serv_date SUM( /bic/znosubasp ) AS /bic/znosubasp
      INTO CORRESPONDING FIELDS OF it_table1
      FROM /bic/azmord2d00
      WHERE serv_date <= wa_result_package-serv_date
      AND me_order_n = wa_result_package-me_order_n
      AND me_itemno = wa_result_package-me_itemno
      GROUP BY me_order_n me_itemno serv_date.
        <result_fields>-me_quanti = it_table1-/bic/znosubasp.
      ENDSELECT.
    ENDLOOP.

  • Index for "group by" statement.

    Hi,
    I have a statement directed at the GLPCP table.
    It sums op the plan number in each month.
    In ABAP it looks like this
    SELECT ryear rprctr racct kostl ps_psp_pnr rfarea
             SUM( hsl01 ) SUM( hsl02 ) SUM( hsl03 )
             SUM( hsl04 ) SUM( hsl05 ) SUM( hsl06 )
             SUM( hsl07 ) SUM( hsl08 ) SUM( hsl09 )
             SUM( hsl10 ) SUM( hsl11 ) SUM( hsl12 )
             INTO TABLE e_t_data
             FROM glpcp
             WHERE kokrs   EQ '0020'
             AND   ryear   IN l_r_year
             AND   rldnr   EQ '8A'
             AND   rrcty   EQ '1'
             AND   rvers   EQ '010'
             AND   rbukrs  EQ '0020'
             GROUP BY ryear rprctr racct kostl ps_psp_pnr rfarea.
    I have created an index on KOKRS, RYEAR, RLDNR, RRCTY, RVERS, RBUKRS. To support the where statement.
    This speeds up the process some but i believe that greater performance can be achieved.
    I ran the expression through the SQL explain routine.
    The path looks like this http://yfrog.com/jdexplainpathj
    It came out with poor performance regarding the group by sentence.
    Explanation of query block number: 1   step: 2
    Query block type is SELECT
    Performance appears to be bad
    Method:
    .          additional sorts needed
    .          for the composite table (current result table)
    .          the sorts are performed
    .          - to meet an GROUP BY
    .          unknown or no prefetch is used
    How can i build an index to support the group by sentence.
    Best Regards
    - Rasmus

    Hi Hermann,
    I can see why you are confused. It is hard to keep track with the changes.
    I will sum up:
    The abap statement.
    SELECT ryear rprctr racct kostl ps_psp_pnr
             SUM( hsl01 ) SUM( hsl02 ) SUM( hsl03 )
             SUM( hsl04 ) SUM( hsl05 ) SUM( hsl06 )
             SUM( hsl07 ) SUM( hsl08 ) SUM( hsl09 )
             SUM( hsl10 ) SUM( hsl11 ) SUM( hsl12 )
             INTO TABLE it_glpcp
             FROM glpcp
             WHERE kokrs   EQ '0020'
             AND   ryear   IN l_r_year
             AND   rldnr   EQ '8A'
             AND   rrcty   EQ '1'
             AND   rvers   EQ '010'
             AND   rbukrs  EQ '0020'
             GROUP BY rprctr racct kostl ps_psp_pnr ryear.
    The SQL statement mad from the abap:
    SELECT                                                                               
    "RYEAR" , "RPRCTR" , "RACCT" , "KOSTL" , "PS_PSP_PNR" ,"RFAREA" , SUM( "HSL01" ) , SUM( "HSL02" ) ,   
      SUM( "HSL03" ) , SUM("HSL04" ) , SUM( "HSL05" ) , SUM( "HSL06" ) , SUM( "HSL07" ) , SUM("HSL08" ) ,   
      SUM( "HSL09" ) , SUM( "HSL10" ) , SUM( "HSL11" ) , SUM("HSL12" )                                      
    FROM                                                                               
    "GLPCP"                                                                               
    WHERE                                                                               
    "RCLNT" = ? AND "KOKRS" = ? AND "RYEAR" =? AND "RLDNR" = ? AND "RRCTY" = ? AND "RVERS" = ? AND "RBUKRS"
      = ?GROUP BY "RYEAR" , "RPRCTR" , "RACCT" , "KOSTL" , "PS_PSP_PNR" ,"RFAREA" FOR FETCH ONLY WITH UR
    The index no. 9.
    http://yfrog.com/jbidx9j
    The hierarchial access path:
    http://yfrog.com/1qexplainj
    This is where I stand at the moment.
    Best Regards,
    Rasmus
    Edited by: Rasmus Stokholm on Apr 7, 2010 1:13 PM

  • How to handle comments in group financial statement

    We have a situation in project where we need to manage comments about organizations financial statement item.
    We are going to use the SAP BCS 6.0 version as a product.
    Please note we can consider any tool like BPC or SSM or anything else if supporting our requirement well.
    We already identified couple of options but we still want to explore and welcome new ideas & experience.
    By now some people might have understood, what I am looking for but below example is for those who never got chance to work in finance but similar kind of situation     
    In the above example comment explain more about the report which may change time to time or in some places it may give explanation about the figures or assessment of a group
    So we are looking for following u2013
    1.     A tool or way to enter comment below the report.
    2.     But there are different groups who enter their comment based on the explanation or assessment submitted by the previous group.
    3.     Meaning approval Process after group u2018Au2019 approver approve then only it goes to Group u2018Bu2019.
    4.     Roll Forward prior period comments at input level
    5.     Submit and Lock comments from lower level to the next level
    6.     Roll up Comments to Assessment
    7.     Lock & Unlock Commentary
    8.     Commentary Review Report.
    9.     It should be stored by time meaning history of the comment should be maintained.
    Kindly please let me know if you have any question or call me if you need more explanation.
    Please note we are open to consider all kind of experience and ideas. So please write if something pop up in your mind.
    Thanks in advance
    Edited by: SMP on Jun 18, 2010 11:03 AM
    Edited by: SMP on Jun 18, 2010 11:05 AM

    Hi SMP,
    I had quite the same need in my last SEM-BCS project.
    Our conclusion was that SEM-BCS was not enough flexible to deal with comments. Indeed, the system performs "integrity checks" when posting transactions.
    Hope it helps
    Regards,
    Thibaud

  • Few sales group monthly statement are not printing

    Client is trying to print a statement for the sales group id xx1,xx2,xx3,xx4 while these come out blank. Actually there have been sales taken place but still it turns out to be blank. Where and how should i check and deal this issue?

    All these sales group share the same revenue account. Will that be a cause for not getting printed?

  • Updating the rows using a group by statement

    i have the following sql:
    select a.lastname, count(*) from ga_to_sali_leads_wrk a
    group by a.lastname, a.address1, a.address2, a.city, a.state
    order by a.lastname, a.address1, a.address2, a.city, a.state
    table ga_to_sali_leads_wrk has many more fields, two of which are ssn and relation_ssn; what i want to do is...for every record in the same group, update field relation_ssn to what's in the ssn field from the first record in the group;
    for example; i have 3 records in the go_to_sali_leads_wrk table
    ssn....relation_ssn.....lastname....address1....address2..city...state
    123.....000.................wills...........12 main....................rose...ga
    333.....000.................wills...........12 main....................rose...ga
    465.....000.................wills...........12 main....................rose...ga
    because the lastname, address1, address2, city and state are all the same, they are grouped together (i'm assuming they are the same family); i want the relation_ssn updated to contain "123" for all 3 records
    Can i do that with an update statement? So far, the update statement hasn't worked.

    SQL> update rt xx
      2  set relation_ssn =
      3  (select ssn from
      4          (select a.*, row_number() over(partition by
      5          a.lastname,a.address1,a.city,a.state order by
      6          a.lastname) rn from rt a)
      7  where rn = 1 and a.lastname = xx.lastname
      8  and a.address1=xx.address1 and a.city=xx.city
      9  and a.state=xx.state);
    and a.state=xx.state)
    ERROR at line 9:
    ORA-00904: "A"."STATE": invalid identifier
    SQL> desc rt
    Name                                      Null?    Type
    SSN                                                CHAR(3)
    RELATION_SSN                                       CHAR(3)
    LASTNAME                                           CHAR(5)
    ADDRESS1                                           CHAR(2)
    ADDRESS2                                           CHAR(4)
    CITY                                               CHAR(4)
    STATE                                              CHAR(2)Devmiral's sql don't use correlated inline view.
    Best regards
    Maxim

  • How to select first row of each group in a group by statement

    Table            
    ProdCode    PackType    BatchCode    ExpDate
    BURSLO               1             BS20GO-2001    01/12/2004
    BURSLO               1             BS20GO-2011    01/01/2007
    BURSLO               2             BS20GO-2027    01/02/2003
    BURSLO               3             BS20GO-2060    01/02/2004
    BURSOI               9             BU10F12    01/02/2006
    BURSOI               9             BU10GO-1301    01/05/2005
    BURSOI              11             BU10GO-131    01/06/2008
    BURSOI               2             BU10GO-1311    01/06/2007
    BURSOI              13             BU10GO-1328    01/07/2006
    Output            
    ProdCode    PackType    BatchCode    ExpDate
    BURSLO               1             BS20GO-2011    01/01/2007
    BURSLO               2             BS20GO-2027    01/02/2003
    BURSLO               3             BS20GO-2060    01/02/2004
    BURSOI               9             BU10F12    01/02/2006
    BURSOI              11             BU10GO-131    01/06/2008
    BURSOI               2             BU10GO-1311    01/06/2007
    BURSOI              13             BU10GO-1328    01/07/2006
    i need first row after group by ProdCode,    PackType and decreading order of ExpDate
    Please Help me.
    Thanks.
         

    Try the below:
    ;With cte
    as
    (Select *,Row_Number()Over(partition by Prodcode,Packtype Order by expdate desc) Rn From Tablename)
    Select * From cte where rn=1

  • Sum a field without using field in group by statement- sql server 2008 SSRS

    I am trying to write a query as follows;
    select todate, sum(entries) as A, sum(entries) as B  *(where dept=HR)
    from table 1
    where dept in(IT,HR)
    group by todate
    here A is summation of all the entries for dept IT and HR
    and want to get B as summation of entries having dept HR only
    Kindly note this sql would be used in ssrs 2008 dataset query.
    Please help.
    Thanks

    Hi, you can write it like this:
    select todate, sum(entries) as A, SUM(CASE WHEN Dept = 'HR' THEN entries ELSE 0 END) as B
    from table 1
    where dept in('IT','HR')
    group by todate
    Martina White

  • Customer-Vendors Group wise statement

    How can i see the Customer-Vendor group wise reports..give me the Tcodes for that...
    Regards
    Devi

    Hi,
    You grp customer via statiscal customer grp.
    When you generate statistics in the logistics information system, the system uses the combination of specified statistics groups to determine the appropriate update sequence. The update sequence in turn determines for exactly which fields the statistics are generated.
    Best Regards
    Ashish Jain

  • Help on group by statement

    I have a table with four columns. I want to select rows if the status is different and the firstname and lastname are same. How do I achieve this.
    For ex: select firstname,lastname,status,sum(amt)
    from table a
    group by 1,2,3
    Thank you,

    Hi,
    create table test
    (firstname varchar2(20),
    lastname varchar2(20),
    status char(1),
    salary number
    insert into test values('John','Boughr','1','100');
    insert into test values('John','Boughr','0','200');
    insert into test values('doug','smiti','1','300');
    insert into test values('doug','smiti','0','400');
    insert into test values('aaa','Boughr','1','100');
    insert into test values('aaa','Boughr','1','100');
    insert into test values('bbbb','Boughr','1','100');
    select a.firstname,a.lastname, sum(a.salary)
    from test a
    where a.firstname||a.lastname
    in (select b.firstname||b.lastname
    from test b
    where a.status <> b.status
    group by a.firstname,a.lastname
    having count(*) > 1
    FIRSTNAME LASTNAME SUM(A.SALARY)
    John Boughr 300
    doug smiti 700
    SQL>

  • Grouping select statement

    Hi! I'm running this query on oracle :
    "select e.userid, d.accountno from userpasswords e, account d where e.tin = d.tin" ,
    but when I sort or group them according to the userids, i kept on getting errors. Does anyone here know what I missed?

    It works for me.
    1* select count(jj.job_title), jj.job_title from  jobs jj group by job_title
    SQL> /
    COUNT(JJ.JOB_TITLE) JOB_TITLE
                1 Accounting Manager
                1 Sales Representative
                1 Purchasing Clerk
                1 Programmer
                1 Public Relations Representative
                1 Administration Vice President
                1 Stock Manager
                1 Marketing Representative
                1 President
                1 Administration Assistant
                1 Finance Manager
    COUNT(JJ.JOB_TITLE) JOB_TITLE
                1 Purchasing Manager
                1 Human Resources Representative
                1 Representive
                1 Accountant
                1 Stock Clerk
                1 Shipping Clerk
                1 Public Accountant
                1 Sales Manager
                1 Marketing Manager
    20 rows selected.

  • Xml clause for group by statement t-sql.

    Hello ,
    I have this data.
    create table #students
    id int identity(1,1) primary key,
    student_id int not null,
    [year] int not null,
    [subject] varchar(50) not null,
    [marks] int not null
    insert into #students
    student_id ,
    [year] ,
    [subject] ,
    [marks]
    values
    (101,2014,'Arts',300),(101,2014,'Science',100),(101,2014,'Maths',400),
    (101,2015,'Arts',200),(101,2015,'Science',300),(101,2015,'Maths',100),
    (102,2014,'Arts',100),(102,2014,'Science',200),(102,2014,'Maths',300),
    (102,2015,'Arts',400),(102,2015,'Science',400),(102,2015,'Maths',200)
    select * from #students
    but i want the output in below format - per student per year the subject and marks should be as xml. Here is sample output.
    student_id [year] subject_marks_xml------------------------------------------------------------
    101 2014 <submarks><submark><subject>Arts</subject><marks>300</marks></submark><submark><subject>Science</subject><marks>100</marks></submark><submark><subject>maths</subject><marks>400</marks></submark></submarks>
    101 2015 <submarks><submark><subject>Arts</subject><marks>200</marks></submark><submark><subject>Science</subject><marks>300</marks></submark><submark><subject>maths</subject><marks>100</marks></submark></submarks>
    102 2014 <submarks><submark><subject>Arts</subject><marks>100</marks></submark><submark><subject>Science</subject><marks>200</marks></submark><submark><subject>maths</subject><marks>300</marks></submark></submarks>
    102 2015 <submarks><submark><subject>Arts</subject><marks>400</marks></submark><submark><subject>Science</subject><marks>400</marks></submark><submark><subject>maths</subject><marks>200</marks></submark></submarks>
    How can bring that up using xquery  ? thanks in advance for any help.

    you can use this
    SELECT student_id,
    [year],
    (SELECT subject,marks
    FROM #students
    WHERE student_id = t.student_id
    AND year = t.year
    FOR XML PATH('submark'),ROOT('submarks'),TYPE)
    FROM (SELECT DISTINCT student_id,
    [year]
    FROM #students)t
    Also see
    http://visakhm.blogspot.in/2013/12/generating-nested-xml-structures-with.html
    http://visakhm.blogspot.in/2014/05/t-sql-tips-fun-with-for-xml-path.html
    Please Mark This As Answer if it solved your issue
    Please Vote This As Helpful if it helps to solve your issue
    Visakh
    My Wiki User Page
    My MSDN Page
    My Personal Blog
    My Facebook Page

  • Count(*) function in select statement having group by condition

    Hi
    I would like to use count(*) in select statement having group by clause. say for example there is a state with a number of cities listed. I would like to get the count of cities for each state.
    the sql stement is grouped by state and it is joined with 5 more tables.
    Thanks
    ps: ignore the previous post

    Assuming there is one record per city per state, then
    SELECT state,count(*)
    FROM state_tbl
    GROUP BY stateWill get one record per state with the number of cities in each state. If you want to join that result set to other tables you need to either create a view with that statement or use an in-line view viz.
    SELECT c.cust_name,c.state,s.num_cities
    FROM customers c,
         (SELECT state,count(*) num_cities
          FROM state_tbl
          GROUP BY state) s
    WHERE c.state = s.stateTTFN
    John

Maybe you are looking for

  • My ipod touch is not found on my pc or in itunes

    Hello This is the situation: I was ready to get my battery loaded but my pc didn't recognized my ipod touch 4th gen. I have windows 7, 64-bit version and newest version of itunes. I have already tried to restart my pc but that didn't work aswell. Is

  • How can I change the app that a .pdf attachment opens in on the fly w/o using Preference Pane?

    I have the need to open some .pdf attachments in firefox (24) and some in Skim, pdf reader. I understand that the opening is set in the Preferences Pane. Is there a way or add on that will allow this on the fly ? Or place the option in the attachment

  • Airport Express vs. D-Link Dir-655 = no xbox connection

    I cant seem to get my airport express to connect to m exisisting network. it just wont work. it keeps asking me to find apple devices at the end of the setup. Meaning it was me to find a airport extreme or time capsule. which i do not own . I own a D

  • Can't See Submit Button?

    Hi I have a form to fill out, I've downloaded Adobe Reader 9, and have completed the form I am not able to save any filled out parts nor does it print fully. I have previous filled out the form using reader 6 ---- it had a submit button that didn;t w

  • Opening documents in separate (non-tabbed) windows

    sorry about this simplistic question, but, how can documents be opened into their own separate window panes? Currently I have to drag each tabbed window out into empty space to establish a newly opened document in a separate window....can such a work