Average of a field by date by site

Our data source has multiple records for a single day (date time stamped) for multiple sites.
For example:
SiteID, Date, Time, CH4
With a record every few minutes.
We need to calculate the average of CH4 for a single day (Date) for each Site (SiteID). The following CTE gets me the most recent value:
WITH GasEngine_CTE 
AS
SELECT CH4, ROW_NUMBER() OVER(PARTITION BY SiteID ORDER BY CAST([Date] AS DATETIME) + CAST([Time] AS DATETIME) DESC) RowNumber
FROM dbo.GasEngine
SELECT *
FROM GasEngine_CTE 
WHERE RowNumber = 1
I need to modify to retrieve the average for each day and each site. I think I need to group (partition) by SiteID and [Date]

Is that you are looking for?
declare @gasengine table(ch4 int, site varchar(2), dt date);
insert into @gasengine
values(1,'S1',getdate()),
(3,'S1',getdate()),
(3,'S1',getdate()-1),
(5,'S1',getdate()-1);
SELECT Site,dt,Avg(CH4)
FROM @gasengine
group by [Site],[Dt]
Satheesh
My Blog |
How to ask questions in technical forum

Similar Messages

  • Average of a field between two dates

    Hi,
    I have a table with two fields. Date Field and Percentage field. For ex,
    Date Percentage
    1/1/2006 11
    1/4/2006 23
    2/4/2006 34
    11/11/2006 354
    1/4/2007 75
    10/09/2007 67
    2/3/2008 876
    I want to find the average(sum of percentage/total no) of Percentage field between two dates.
    I am passing only the end date. And, the start date I have to find according to the end date.
    For ex,if I am passing the end date as 10/09/2007, starting date should be 1/4/2007.
    And, if I am passing the end date as 11/11/2006, starting date should be 1/4/2006.
    For end date 2/3/2008, start date should be 1/4/2007.
    Starting date is taken as by considering the year end as April to March. So, I have to retrieve the average of the percentage field from April to the selected date as end date.
    thanks

    Getting the sum, number of rows and average since the last 1st of April to the current date :
    SQL> with tbl as
      2  (select to_date('01/01/2006','dd/mm/yyyy') as dt, 11  prct from dual union all
      3   select to_date('01/04/2006','dd/mm/yyyy') as dt, 23  prct from dual union all
      4   select to_date('02/04/2006','dd/mm/yyyy') as dt, 34  prct from dual union all
      5   select to_date('11/11/2006','dd/mm/yyyy') as dt, 354 prct from dual union all
      6   select to_date('01/04/2007','dd/mm/yyyy') as dt, 75  prct from dual union all
      7   select to_date('10/09/2007','dd/mm/yyyy') as dt, 67  prct from dual union all
      8   select to_date('02/03/2008','dd/mm/yyyy') as dt, 876 prct from dual)
      9  select dt, prct,
    10         sum(prct) over (order by dt range between dt-add_months(trunc(add_months(dt,-3),'yyyy'),3) preceding and current row) sum_prct,
    11         count(prct) over (order by dt range between dt-add_months(trunc(add_months(dt,-3),'yyyy'),3) preceding and current row) nb_prct,
    12         avg(prct) over (order by dt range between dt-add_months(trunc(add_months(dt,-3),'yyyy'),3) preceding and current row) avg_prct
    13  from tbl;
    DT             PRCT   SUM_PRCT    NB_PRCT   AVG_PRCT
    01/01/06         11         11          1         11
    01/04/06         23         23          1         23
    02/04/06         34         57          2       28,5
    11/11/06        354        411          3        137
    01/04/07         75         75          1         75
    10/09/07         67        142          2         71
    02/03/08        876       1018          3 339,333333
    7 rows selected.Nicolas.

  • Moving average price  based on date range, site and article.

    Hi ABAPers,
    I am working on SKU wise sales report. Based on user input of date range ,site and article I fetch data from VBRP table i.e., (billing data from stores) . I have searched a lot to find MAP but dint get convincing solution.
    I tried to get data from MBEW-VERPR but that doesnot give MAP for a given date. I also tried with condition record table and KONP table but not helpful.
    I also got to know about s031 and LIS configuration I am not sure whether functional consultant should do the changes.
    Kindly help me in obtaining the MAP for particular bill date, article and site(store).
    Regards,
    Dep

    You can found the moving average price in MBEW (current) and MBEWH (history table)
    The first goods movement after the period closing program updates the period in MBEW and writes the data of the previous period to table MBEWH
    - If you actually need map on a daily (or less) basis, you will have to calculate it from MBEW, MBEWH, MSEG and BSIM (...)
    - You could also look for the actual cost in MSEG related to records of VBRP.
    Regards,
    Raymond

  • On load, getting error:  Field in data file exceeds maximum length

    Oracle Database 11g Enterprise Edition Release 11.2.0.3.0 - 64bit Production
    PL/SQL Release 11.2.0.3.0 - Production
    CORE    11.2.0.3.0    Production
    TNS for Solaris: Version 11.2.0.3.0 - Production
    NLSRTL Version 11.2.0.3.0 - Production
    I'm trying to load a table, small in size (110 rows, 6 columns).  One of the columns, called NOTES is erroring when I run the load.  It is saying that the column size exceeds max limit.  As you can see here, the table column is set to 4000 Bytes)
    CREATE TABLE NRIS.NRN_REPORT_NOTES
      NOTES_CN      VARCHAR2(40 BYTE)               DEFAULT sys_guid()            NOT NULL,
      REPORT_GROUP  VARCHAR2(100 BYTE)              NOT NULL,
      AREACODE      VARCHAR2(50 BYTE)               NOT NULL,
      ROUND         NUMBER(3)                       NOT NULL,
      NOTES         VARCHAR2(4000 BYTE),
      LAST_UPDATE   TIMESTAMP(6) WITH TIME ZONE     DEFAULT systimestamp          NOT NULL
    TABLESPACE USERS
    RESULT_CACHE (MODE DEFAULT)
    PCTUSED    0
    PCTFREE    10
    INITRANS   1
    MAXTRANS   255
    STORAGE    (
                INITIAL          80K
                NEXT             1M
                MINEXTENTS       1
                MAXEXTENTS       UNLIMITED
                PCTINCREASE      0
                BUFFER_POOL      DEFAULT
                FLASH_CACHE      DEFAULT
                CELL_FLASH_CACHE DEFAULT
    LOGGING
    NOCOMPRESS
    NOCACHE
    NOPARALLEL
    MONITORING;
    I did a little investigating, and it doesn't add up.
    when i run
    select max(lengthb(notes)) from NRIS.NRN_REPORT_NOTES
    I get a return of
    643
    That tells me that the largest size instance of that column is only 643 bytes.  But EVERY insert is failing.
    Here is the loader file header, and first couple of inserts:
    LOAD DATA
    INFILE *
    BADFILE './NRIS.NRN_REPORT_NOTES.BAD'
    DISCARDFILE './NRIS.NRN_REPORT_NOTES.DSC'
    APPEND INTO TABLE NRIS.NRN_REPORT_NOTES
    Fields terminated by ";" Optionally enclosed by '|'
      NOTES_CN,
      REPORT_GROUP,
      AREACODE,
      ROUND NULLIF (ROUND="NULL"),
      NOTES,
      LAST_UPDATE TIMESTAMP WITH TIME ZONE "MM/DD/YYYY HH24:MI:SS.FF9 TZR" NULLIF (LAST_UPDATE="NULL")
    BEGINDATA
    |E2ACF256F01F46A7E0440003BA0F14C2|;|DEMOGRAPHICS|;|A01003|;3;|Demographic results show that 46 percent of visits are made by females.  Among racial and ethnic minorities, the most commonly encountered are Native American (4%) and Hispanic / Latino (2%).  The age distribution shows that the Bitterroot has a relatively small proportion of children under age 16 (14%) in the visiting population.  People over the age of 60 account for about 22% of visits.   Most of the visitation is from the local area.  More than 85% of visits come from people who live within 50 miles.|;07/29/2013 16:09:27.000000000 -06:00
    |E2ACF256F02046A7E0440003BA0F14C2|;|VISIT DESCRIPTION|;|A01003|;3;|Most visits to the Bitterroot are fairly short.  Over half of the visits last less than 3 hours.  The median length of visit to overnight sites is about 43 hours, or about 2 days.  The average Wilderness visit lasts only about 6 hours, although more than half of those visits are shorter than 3 hours long.   Most visits come from people who are fairly frequent visitors.  Over thirty percent are made by people who visit between 40 and 100 times per year.  Another 8 percent of visits are from people who report visiting more than 100 times per year.|;07/29/2013 16:09:27.000000000 -06:00
    |E2ACF256F02146A7E0440003BA0F14C2|;|ACTIVITIES|;|A01003|;3;|The most frequently reported primary activity is hiking/walking (42%), followed by downhill skiing (12%), and hunting (8%).  Over half of the visits report participating in relaxing and viewing scenery.|;07/29/2013 16:09:27.000000000 -06:00
    Here is the full beginning of the loader log, ending after the first row return.  (They ALL say the same error)
    SQL*Loader: Release 10.2.0.4.0 - Production on Thu Aug 22 12:09:07 2013
    Copyright (c) 1982, 2007, Oracle.  All rights reserved.
    Control File:   NRIS.NRN_REPORT_NOTES.ctl
    Data File:      NRIS.NRN_REPORT_NOTES.ctl
      Bad File:     ./NRIS.NRN_REPORT_NOTES.BAD
      Discard File: ./NRIS.NRN_REPORT_NOTES.DSC
    (Allow all discards)
    Number to load: ALL
    Number to skip: 0
    Errors allowed: 50
    Bind array:     64 rows, maximum of 256000 bytes
    Continuation:    none specified
    Path used:      Conventional
    Table NRIS.NRN_REPORT_NOTES, loaded from every logical record.
    Insert option in effect for this table: APPEND
       Column Name                  Position   Len  Term Encl Datatype
    NOTES_CN                            FIRST     *   ;  O(|) CHARACTER
    REPORT_GROUP                         NEXT     *   ;  O(|) CHARACTER
    AREACODE                             NEXT     *   ;  O(|) CHARACTER
    ROUND                                NEXT     *   ;  O(|) CHARACTER
        NULL if ROUND = 0X4e554c4c(character 'NULL')
    NOTES                                NEXT     *   ;  O(|) CHARACTER
    LAST_UPDATE                          NEXT     *   ;  O(|) DATETIME MM/DD/YYYY HH24:MI:SS.FF9 TZR
        NULL if LAST_UPDATE = 0X4e554c4c(character 'NULL')
    Record 1: Rejected - Error on table NRIS.NRN_REPORT_NOTES, column NOTES.
    Field in data file exceeds maximum length...
    I am not seeing why this would be failing.

    HI,
    the problem is delimited data defaults to char(255)..... Very helpful I know.....
    what you need to two is tell sqlldr hat the data is longer than this.
    so change notes to notes char(4000) in you control file and it should work.
    cheers,
    harry

  • Issue with list saving data after sites upgrade from sharepoint 2010 to sharepoint 2013

    Issue with list saving data after sites upgrade from sharepoint 2010 to sharepoint 2013 
    Newform.aspx of list:-
    Custom List is not saving data sometimes in the new form after 15 minutes and only blank entry record got created without saving data, even though some columns are mandatory fields?

    Hello dcakumar,
    Sounds like a strang issue. If you can reproduce this can you see some errors in the ULS logs?
    - Dennis | Netherlands | Blog |
    Twitter

  • Required field has data but not accepting it

    I just launched a site and discovered that my forms page won't work. The First Name field has data in it but when clicking the submit button the page doesn't advance and the red font indicates the Requied field needs data.
    Please help. I just launched site and then discovered since couldn't test until now.
    Sean

    http://moneyorganizerprocom.businesscatalyst.com/14-day-registration.html
    Sean Allen
    Money Organizer Pro
    Phone 866.321.4764 x700
    e-mail ~  <mailto:[email protected]> [email protected]
    website~  <http://www.moneyorganizerpro.com/> www.moneyorganizerpro.com

  • DSO - What key fields and data fields in dso

    Hi experts,
    I need to create a dso in between the cube and 2 data sources(2lis_11_vaitm, 2lis_12_vcscl) to stage the data. My question is: what key fields and data fields to choose for the dso? is there a standard dso to copy? please explain in detail the model to set up, whether to connect both the ds's to dso and then to cube or one ds to dso and the other to the cube. more details will help.

    Check this for standard DSO:
    http://help.sap.com/saphelp_nw04/helpdata/en/43/fcdc387f34384f94c3227baf3837a8/content.htm
    Thanks...
    Shambhu

  • Data in one field requires data in another field

    I am trying to build a form that forces data entry (text)
    into a field if a previous ( or other ) field has data in it.
    Example: If there is data in the "Full Name" block, you have
    to put data in the "Crew Name" block.
    If the "Crew Name" block contains data, all is fine,
    otherwise an error message is created.
    Also, how do I validate this ( is it even required ? )
    Thanks ! ~The Noob~

    Droto wrote:
    > I am trying to build a form that forces data entry
    (text) into a field if a
    > previous ( or other ) field has data in it.
    > Example: If there is data in the "Full Name" block, you
    have to put data in
    > the "Crew Name" block.
    > If the "Crew Name" block contains data, all is fine,
    otherwise an error
    > message is created.
    > Also, how do I validate this ( is it even required ? )
    > Thanks ! ~The Noob~
    >
    Are you saying that "Full Name" is not required? But if there
    is data in
    the "Full Name" field, then "Crew Name" is required?
    Mick

  • Key fields and data fields in a DSO  ??

    i have a question regarding key fields and data fields in a Standard DSO...
    i am using 2 datasources to build a open sales report 2LIS_11_VASTH  and  2LIS_11_VASTI   i am pulling in data from these 2 data sources to a DSO and i am wondering what infoobjects should be in the key fields and data fields .....does this reflect back to table VBUK and VBUP tables and does the key field in the DSO have to be the key fields in VBUK and VBUP tables  ????  or what really should be included as key fields and data fields   ????  
    please help....

    If you look at the various SD tables, VBELN and POSNR are commonly used as the document number and document line item.
    For VBAP and VBUP, it's referring to the Sales Order Line Item with the columns VBELN and POSNR as the key for both tables. However, if you look at the LIPS table, which is the Delivery Line Item table, it too has VBELN and POSNR as the key. Likewise, the VTTP table, which is the Shipment Line Item table, also has VBELN and POSNR as the key.
    While using RSOSFIELDMAP as a map is a fairly good "rule of thumb", it still needs to be used with a level of skepticism.

  • Prerequsites for deciding Key fields and data fields

    Hi
    I would like to know the criteria to decide upon KEY fields and Data fields for an infoprovider.

    Hi,
    What is a Key field in a Database and How should I choose one?
    Keys are crucial to a table structure for many reasons, some of which are identified below:
    They ensure that each record in a table is precisely identified.
    They help establish and enforce various types of integrity.
    They serve to establish table relationships.
    Datafields may be Charecteristics and it may be keyfigures
    Regards,
    Marasa.

  • Chart report Condition fields and Data fields

    Hi all,
    i have tried chart report by adding two condion fields and one data field, the report is more meaning full in this scenario. the first condition field is taken as x-axis, the 2nd condition fields is taken as legend.
    while adding more condition fields and data fields, i feel its not showing meaningfull data.
    can anyone explain how the condition fields and data fileds are manipulated by crystal report.
    i am using CR XI R2 Server.
    Thanks
    Padmanaban V

    i am using Crystal Report XI R2 RAS Embedded in my server.
    as we can add any number condition fields programatically using the method
    ConditionField.Add(FieldObj), i would like to know how these fields are manipulated internally by the RAS server.
    that means, what is the significance of condition fieldobject 1, condition fieldobject 2,condition fieldobject 3 etc...
    if i add more than two condition fields , RAS Chart Report always returns 0 as legend value for all legends.
    Thanks in advance
    Regards,
    Padmanaban V
    Edited by: Padmanaban Viswanathan on Dec 22, 2008 9:53 AM

  • Releation between fields and data element

    Dear Abapers,
    What is the relation between the fields and data element,  while cretion of fields system will ask the data element, can we have one data element to more than one fields.  Can you plese explain me.
    Regards

    Hi,
    data elements are structures defined in SAP Dictionary. 
    Fields you meen in a table? or in programs? in both places you create in reference to SAP Dictionary. 
    data element char20.  TEXT20
    Programs  data:  l_text type char20.
    Tables  ... field   ZTEXT  type CHAR20...TEXT20

  • Identify key fields and data fields

    Hi
    i have datasource 0co_om_cca_9 .
    i want build 1 DSO, how can i identify what are key fields and data fields to build DSO based on that datasource.

    Hi sunnel,
    The DSO are like 2-D database tables.
    We use the technical keys here in counterpart to the business keys in Infocubes.
    The key fields are the one based on which the records are identified uniquely in the database table.
    And the data fields are the ones which are aggrgated or summarised or overwritten based on the value in key filed.
    For example:
    The ID no.s of the employees will be unique and it can be used as a key field.
    The feilds like the Salary taken by the employee every month :"SALARY"
    and the no. of leaves they taken: " NO. OF LEAVES" can be used as data fields.
    So that the salary or the leaves taken by a particular employee can be aggregated based on her/his ID no.
    The key fields in DSO doesnty mean Key figures.The key field means any unique key or a key based on which the records are sorted in the DSO
    And key figures are the data fields.Some of the Characteristics can also be data fields in DSO.
    Please give points if u r satisfied wit the information
    Also let me know if u hav any doubt and if any thing is wrong.
    Regards,
    Kalpana M

  • Defining Key -field and data fields

    Hi all
    i have to define Key-Fields and data-Fields for a DSO(say DSO3).
    DSO1 is a combination of DSO2 and DSO3..
    DSO1 and DSO2 are SAP defined DSOs.
    DSO3 is a User defined DSO.
    my assumption:
       DSO3 has 30 fields
       DSO2 has 16 fields.
       can i create the DSO3 with remaining 14 fields which is there in DSO1?
       or i have to create the DSO3 with 30 fields(all DSO1 fields).
    can any body explain....
    Thanks & Regards
    krishna

    The problem is not how many fields you create where, the issue is where is the data is going to come from.
    Since you data is going from DSO3 to DSO1and if the field is already getting populated in DSO1 from DSO2, then you don't have to worry about populating those fields again, unless and otherwise you want to overwrite them.
    Remember any fields exist in both DSO3 and DSO2 which overlapping will be overwritten by the latest update.
    Again, going back to your question, you should consider does your datasource has missing fields (14 of them).
    thanks.
    Wond

  • Field in data file exceeds maximum length

    Hi,
    I am trying to run the following SQL*Loader control job on my Oracle 11gR2 . Running the SQL*Loader control job results in the ‘Field in data file exceeds maximum length’ error message. Below, I am listing the control file.Please Suggest. Thanks
    It's giving me an error when I run SQL Loader on it,
    Record 61: Rejected - Error on table RMS_TABLE, column GEOM.SDO_POINT.X.
    Field in data file exceeds maximum length.
    Here is my SQL Loader Control file,
    LOAD DATA
    INFILE *
    TRUNCATE
    CONTINUEIF NEXT(1:1) = '#'
    INTO TABLE RMS_TABLE
    FIELDS TERMINATED BY '|'
    TRAILING NULLCOLS (
       Status NULLIF Status = BLANKS,
       Score,
       Match_type NULLIF Match_type = BLANKS,
       Match_addr NULLIF Match_addr = BLANKS,
       Side NULLIF Side = BLANKS,
       User_fld NULLIF User_fld = BLANKS,
       Addr_type NULLIF Addr_type = BLANKS,
       ARC_Street NULLIF ARC_Street = BLANKS,
       ARC_City NULLIF ARC_City = BLANKS,
       ARC_State NULLIF ARC_State = BLANKS,
       ARC_ZIP NULLIF ARC_ZIP = BLANKS,
       INCIDENT_N NULLIF INCIDENT_N = BLANKS,
       CDATE NULLIF CDATE = BLANKS,
       CTIME NULLIF CTIME = BLANKS,
       DISTRICT NULLIF DISTRICT = BLANKS,
    LOCATION
    NULLIF LOCATION = BLANKS,
       MAPLOCATIO
    NULLIF MAPLOCATIO = BLANKS,
       LOCATION_T
    NULLIF LOCATION_T = BLANKS,
       DAYCODE
    NULLIF DAYCODE = BLANKS,
       CAUSE
    NULLIF CAUSE = BLANKS,
       GEOM COLUMN OBJECT
         SDO_GTYPE       INTEGER EXTERNAL,
         SDO_POINT COLUMN OBJECT
           (X            FLOAT EXTERNAL,
            Y            FLOAT EXTERNAL)
    CREATE TABLE RMS_TABLE (
      Status VARCHAR2(1),
      Score NUMBER,
      Match_type VARCHAR2(2),
      Match_addr VARCHAR2(120),
      Side VARCHAR2(1),
      User_fld VARCHAR2(120),
      Addr_type VARCHAR2(20),
      ARC_Street VARCHAR2(100),
      ARC_City VARCHAR2(40),
      ARC_State VARCHAR2(20),
      ARC_ZIP VARCHAR2(10),
      INCIDENT_N VARCHAR2(9),
      CDATE VARCHAR2(10),
      CTIME VARCHAR2(8),
      DISTRICT VARCHAR2(4),
      LOCATION VARCHAR2(128),
      MAPLOCATIO VARCHAR2(100),
      LOCATION_T VARCHAR2(42),
      DAYCODE VARCHAR2(1),
      CAUSE VARCHAR2(17),
      GEOM MDSYS.SDO_GEOMETRY);

    Hi,
    Looks like you have a problem with record 61 in your data file. Can you please post it in reply.
    Regards
    Ivan

Maybe you are looking for