Difference of last 2 rows

Hi i have a table which includes meter reading of different meters. When i give the meter id i need to take the last 2 meter reading values . My table structure and datas are
CREATE TABLE MeterReading
ReadingID int,
MeterID int,
DataCounter int,
Value numeric(16,4)
INSERT INTO MeterReading
VALUES(1, 1, 1, 102.45)
INSERT INTO MeterReading
VALUES(2, 2, 1, 110.45)
INSERT INTO MeterReading
VALUES(3, 1, 2, 110.58)
INSERT INTO MeterReading
VALUES(4, 2, 2, 115.89)
INSERT INTO MeterReading
VALUES(5, 1, 4, 120.00)
INSERT INTO MeterReading
VALUES(6, 2, 4, 116.23)
Here i need the difference of latest (based on DataCounter) difference of Values corresponding MeterID
select top 2 * from MeterReading
where MeterID = 1
order by DataCounter desc
I give the select query. so that i need to take the diffrence of these selected rows' Values. Always the latest value is larger

Sorry friends. I didn't got your way. Here i explain my scenario. Please advice me the correct way so that i can change more cursor queries in my work. I also knew that cursor is not good but not got any suitable approach for this.
Scenario:
   I have 3 table named Table1, Table2 and Table3.
Table 1 is the log table which the data is inserted by windows service from third party.This table logs all the data from the service so that same data can be duplicated. Because third party send the data 3 times to avoid data loss. Windows service send
the acknowledge but some time if the acknowledge delayed or failed seconds time the same data cam,e and log here. The table have 'ProcessStatus' which have value '0'when data is inserted.
To process log table (table1) i need to write one procedure and configure the procedure as SQL job. Here is all the logic.
Step1 : I need to iterate all the rows in table1 which have processstatus is '0'
step2 :Based on the data type (this is column in the table1) insertion is in different table and logic is different.
If data type 1
Step 2.1 First need to check whether data is already exist in the intermediate table (table2). If not found insert the data to table2. Otherwise insert error in the error log table
Step 2.2 Take the last entries from the table2 (based on the constraints like gave in the query question..eg: MeterID) and found the difference of values and insert one record in the table3 which includes the difference, start time as first entry time and
end time as last entry time. So the table 3 have energy consumption.
Step 3....Like data type 2 etc...
Step 4: Update log table record's processstatus as 1.
I think you got the scenario. Please advise me how i change these much operations from the cursor to each set queries

Similar Messages

  • Difference of last 2 Rows with Start and End Time

    Hi all,
      This question is an extention to the below question
    http://social.msdn.microsoft.com/Forums/en-US/ca938faf-49a7-4212-afd2-19046cbfcc8b/difference-of-last-2-rows?forum=transactsql
    I got the difference of last 2 rows from the above question. But now the table added with one field StartTime. The final table is
    CREATE TABLE MeterReading
    ReadingID int,
    MeterID int,
    DataCounter int,
    StartTime datetime,
    Value numeric(16,4)
    As per the my first thread i got the best answer like below
    SELECT MeterID, SUM(CASE WHEN Recency = 1 THEN Value ELSE -Value END)
    FROM (
    select DISTINCT MeterID, Value, DENSE_RANK() OVER (PARTITION BY MeterID ORDER BY StartTime DESC) 'Recency'
    from MeterReading
    ) x
    WHERE Recency IN (1,2)
    GROUP BY MeterID
    Now i need to add StartTime to the result. The expectation is, it will take the difference of last and second last record. So i need the starttime as secondlast record starttime and endtime as last record startime. Please help me

    I got a solution like below
    SELECT
    y.ProcessParameterID
    ,MIN(y.StartTime) StartTime
    ,MAX(y.EndTime) EndTime
    ,SUM(y.Value) Value
    FROM
    SELECT
    ProcessParameterID
    ,(CASE WHEN Recency = 2 THEN StartTime ELSE null END) StartTime
    ,(CASE WHEN Recency = 1 THEN StartTime ELSE null END) EndTime
    , SUM(CASE WHEN Recency = 1 THEN Value ELSE -Value END) Value
    FROM (
    select DISTINCT ProcessParameterID, StartTime, Value, DENSE_RANK() OVER (PARTITION BY ProcessParameterID ORDER BY StartTime DESC) 'Recency'
    from LT_LAEMI_HWT_Readings
    ) x
    WHERE Recency IN (1,2)
    GROUP BY ProcessParameterID
    , Recency
    , StartTime
    ) y
    GROUP BY ProcessParameterID
    Can you advice me, is this the correct way or any alternative short method

  • How to populate the last empty row in Excel without using Report Generation Kit

    I wrote  a Labview SUb Vi that uses Report Generation Toolkit that is not loaded on the test stand. I am looking to convert it from Report Generation Vi like New Report,  Append Table to Report, Dispose Report. The tunneling through all the report generation Vis seems extensive. Code is attached. Thanks, Greg
    Greg

    Thank you that was a big help...
    I used the Excel Forum to get a lot of great ideas.  My code is almost working.
    There is a 2-D String Array that represents the String data that I am exporting to the Excel File Sheet 1 - 5.
    I am attempting to determine the last populated row in sheet 1 then populate the next row of Sheet 1.  Since all 5 sheets are populated every time, I should not have to search every sheet for the last row.
    I am getting two row populated on sheet 1 with seeming the same data.
     I found an AXExcelWrite2D ArrayWorksheet.vi that I thought would work.  I think there is a Table  determination that is causing me problems.  The link is http://lavag.org/topic/13324-labview-and-excel-activex-or-ado/.  The Application Invoke Node has a convert formula with "FromReferenceStyle" with R1C1 Attached to it.   I am not sure what this function is doing.  When I try to bring the function help up, there is a missing file.
    I am including both the new active x vi and the report generation vi.   Report Generation VI works.
    I would appreciate any assistance I can get on this.
    Thanks
    Greg
    Greg
    Attachments:
    REPU Test Data Population using Active X Write Save.vi ‏92 KB
    REPU Test Data Population.vi ‏60 KB

  • How to delete duplicate rows in oracle and retaining last duplicate rows

    Hi,
    I'm having millions of records in the table .Some duplicate values/rows are inserted in it.
    I just want to delete duplicate rows but also want to retain the last duplicate row.
    For eg if one record is found three times ,i want to delete first and second record and retain
    the third one i.e the last inserted one.
    Regards
    Paramdeep Singh

    user13310594 wrote:
    Hi,
    I'm having millions of records in the table .Some duplicate values/rows are inserted in it.
    I just want to delete duplicate rows but also want to retain the last duplicate row.
    For eg if one record is found three times ,i want to delete first and second record and retain
    the third one i.e the last inserted one.Hi Paramdeep,
    To start with, since you do not wish to keep multiple rows with same values, why allow them to get inserted in the first place?
    Wouldn't it be easier to block duplicate rows from inserting by creating a Unique constraint on Column(s) that define a row as duplicate, then rather deleting duplicate rows periodically?
    For deleting duplicate rows, there are N number of techniques available. Always remember, you need to have a rigid criteria that marks row as duplicate.
    [url http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:15258974323143]this is one recomended by tom for large tables.
    Vivek L

  • How can I get only the last 2 rows?

    How can I narrow down a query to get only the last two rows in a table ?
    Thanks,
    Mohan

    Thanks a lot Ram for your suggestion but already I have a query which returns a set of rows, of which I would like to further filter and get the last two rows
    <BLOCKQUOTE><font size="1" face="Verdana, Arial">quote:</font><HR>Originally posted by Ramanuj Bangad ([email protected]):
    try out something like this if it helps.
    Example:
    select * from users
    where rownum <= (select count(*) from users)
    minus
    select * from users
    where rownum <= (select count(*) -2 from users )
    <HR></BLOCKQUOTE>
    null

  • How to get the values of last selected row in Table?

    Hi,
    I have one editable table , where i have Create, Delete and Commit operation on it.
    When i am clicking on Create button it add new row to my table.
    But I want the value of my last selected row from the table in my Bean.
    Can anyone suggest me please....... its urgent
    Jdev:- 11.1.1.0.3
    Thanks,
    Ramit

    just get this code empTable is the table binding
                    RowKeySet rks = new RowKeySetImpl(); 
                    CollectionModel model = (CollectionModel)empTable.getValue(); 
          RowKeySet selectedRowKeys = empTable.getSelectedRowKeys();
          if (selectedRowKeys != null)
                Iterator iter = selectedRowKeys.iterator();
                if (iter != null && iter.hasNext())
                  empTable.setRowKey(iter.next());
                  model.setRowIndex(empTable.getRowIndex()); 
                  Object key = model.getRowKey(); 
                  rks.add(key); 
                    empTable.setSelectedRowKeys(rks); 
          AdfFacesContext.getCurrentInstance().addPartialTarget(empTable);
        public void setEmpTable(RichTable empTable) {
            this.empTable = empTable;
        public RichTable getEmpTable() {
            return empTable;
        }

  • What's the difference between last seen and last a...

    What's the difference between  last seen and last activity by a contact's name?  Please be very specific  Many thanks.

    BUMP -> I'd also like to know the answer to this question.  Thanks, Lance

  • How to: Display Last n Rows in a table

    I am currently running Crystal Reports XI and have been tasked with developing a report that displays only the last 30 rows in a table in ascending order (the records are used for showing data trends over time in a line graph). I have created a Command to extract the records, and by using the TOP 30 statement I can get the first 30 rows in proper order; however, in order to get the last 30 rows I have to sort the records in descending order. This gives me the last 30 rows that I need, but the data is in descending order. Is there another way to get the last 30 rows in a table so that the records come out in ascending order?
    The Command I am using looks like this:
    SELECT TOP 30 ROWID FROM MYTABLE ORDER BY ROWID DESC
    (The ROWID field is alpha numeric)

    Hi,
    Create a Group based on Rowid in the order-Ascending. This Group should contain all the fields that you require to print along with Rowid.  Therafter insert Summary like sum,count etc for for any field within the group of the type numbervar(numeric). This would activate the Group Sort Expert in the Report Menu. Click on it and select Bottom N (with N as 30) within nature of Sort and suppy the fieldname as Rowid.
    Hope this solves.....
    Thanks,
    Amogh.

  • Last Inserted Row in a Table

    Hi,
    I want to select only the last inserted row in a table. Can anybody help me how can i get it.
    Eg
    select * from emp;
    empno ename sal
    12 abc 100
    13 xyz 200
    Now i have inserted a row as
    Insert into emp values (14,'Rohit',500);
    So i only want to select the last inserted row i.e.. empno 14 (in this case).
    Thanks
    Bye
    Rohit Taneja

    Thanks to all for replying.
    But the result is not which i desire.
    I have deleted the existing row in the same table as
    SQL> Delete from emp where empno = 13;
    1 row deleted.
    Then i inserted a new row as
    SQL> insert into emp values(10,'SRI',200);
    1 row created.
    Then i committed the work
    SQL> commit;
    Commit complete.
    But still am getting the last row as
    SQL> select * from emp
    where rowid=(select max(rowid)
    from emp);
    EMPNO ENAME SAL
    14 ROHIT 500
    as the solution.
    But here i am supposed to get the row with empno 10.
    I have tried both the queries and still geting the same result.
    Please look aat it again,
    Thanks in advance
    Bye
    Rohit Taneja
    Hi,
    I want to select only the last inserted row in a
    table. Can anybody help me how can i get it.
    Eg
    select * from emp;
    empno ename sal
    12 abc 100
    13 xyz 200
    Now i have inserted a row as
    Insert into emp values (14,'Rohit',500);
    So i only want to select the last inserted row i.e..
    empno 14 (in this case).
    Thanks
    Bye
    Rohit Taneja

  • Query for last four rows?

    please write query for get the last four rows from a table

    ratnakar wrote:
    please write query for get the last four rows from a tablelast 4 rows is indeterminate.
    rows in a table are like balls in a basket.
    which are last 4 balls in any basket?
    Handle:     ratnakar
    Email:     [email protected]
    Status Level:     Newbie
    Registered:     Aug 27, 2012
    Total Posts:     34
    Total Questions:     16 (11 unresolved)
    why so MANY unanswered questions?

  • GridControl show the last two rows in blank

    I'm using JDeveloper 3.2.2 with jdk 1.3 developing a swing
    application.
    I have a form with a gridControl binded to one view of my bc4j
    application module.
    When the number of records from the view excedes the maximum
    number of rows visibles in the area of the gridControl the last
    two rows of the gridControl are showed blank.
    There is no problem when I scroll through the grid control.
    This problem doesn't appear using JDK 1.2.2, provided with
    Jdeveloper, but I would like to use 1.3.1.
    Thanks in advance
    Alex.

    You don't need to do Sum for this, you should use Sum for all rows purpose only..
    $.rawValue = subform_Hidden.sub_SupportTotals.tbl_SupportSubtotals.DataRow[0]. SUBTOTAL +  subform_Hidden.sub_SupportTotals.tbl_SupportSubtotals.DataRow[1].SUBT OTAL

  • How to fetch last inserted row in MySQL

    Hi,
    I am trying to get the last inserted row in MySql..but not able to fetch it.
    this is what i used
    i have one column order_id which is auto_increment
    SELECT * FROM tablename WHERE order_id=(SELECT MAX(order_id) FROM tablename)
    any help is appreciated .
    the usage of lastinsert() method is also not successful
    chintan

    Hello
    Given you have a date column, you can use it to determine the latest row. However, there is still a chance that two rows were inserted at exactly the same time in which case you will need something in addition to your date column to decide which is the latest...
    The first option uses a sub query and the second uses analytics, as does the 3rd - however with the 3rd, if 2 rows have exactly the same date and time, it will pick one at random unless you include another column in the order by to determine the latest...
    select
    FROM
        your_table
    WHERE
        your_date_column = (SELECT MAX(your_date_column) from your_table)
    SELECT
    FROM
            select
                a.*,
                MAX(your_date_column) OVER() max_date_column
            FROM
                your_table a
    WHERE
        your_date_column = max_date_column
    SELECT
    FROM
            select
                a.*,
                ROW_NUMBER OVER(ORDER BY your_date_column DESC) rn
            FROM
                your_table a
    WHERE
        rn = 1HTH
    David

  • Getting last x rows written to the DB

    Hi all
    I have written some data to my table and wanted to know the best way of getting the last x rows written to the table?
    Thanks for any suggestions.

    Probably I come a little late here, but here is my suggestion:
    WITH data AS (SELECT SYSDATE + 1 / 24 AS col1
                    FROM DUAL
                  UNION ALL
                  SELECT SYSDATE + 2 / 24 AS col1
                    FROM DUAL
                  UNION ALL
                  SELECT SYSDATE + 6 / 24 AS col1
                    FROM DUAL
                  UNION ALL
                  SELECT SYSDATE + 1 / 24 AS col1
                    FROM DUAL
                  UNION ALL
                  SELECT SYSDATE + 4 / 24 AS col1
                    FROM DUAL
                  UNION ALL
                  SELECT SYSDATE + 5 / 24 AS col1
                    FROM DUAL
                  UNION ALL
                  SELECT SYSDATE + 6 / 24 AS col1
                    FROM DUAL
                  UNION ALL
                  SELECT SYSDATE + 2 / 24 AS col1
                    FROM DUAL
                  UNION ALL
                  SELECT SYSDATE + 1 / 24 AS col1
                    FROM DUAL
                  UNION ALL
                  SELECT SYSDATE + 3 / 24 AS col1
                    FROM DUAL
                  UNION ALL
                  SELECT SYSDATE + 1 / 24 AS col1
                    FROM DUAL
                  UNION ALL
                  SELECT SYSDATE + 3 / 24 AS col1
                    FROM DUAL
                  UNION ALL
                  SELECT SYSDATE + 1 / 24 AS col1
                    FROM DUAL
                  UNION ALL
                  SELECT SYSDATE + 6 / 24 AS col1
                    FROM DUAL)
    SELECT *
      FROM (SELECT col1,
                   DENSE_RANK () OVER (ORDER BY col1 DESC) AS rnk
              FROM data)
    WHERE rnk = 1
    /So, if you have some sort of data and a column of datetime type, you can sort the data in descending order by this datetime column and then take the "last" rows, e.g. the rows which value in the datetime column is the oldest one.

  • First And Last Visible Row - JTable

    I have a JTable on a ScrollPane backed by a TableModel, which provides a view on a potentialy large database table. It would be very helpfull if I could find the First and the Last visible row in the JTable every time it makes an elementAt request via TableModel interface, so that the cache underneeth the TableModel could make more intelegent descissions as to when to request more rows from the DB. I cant seem to see any methods on JTable or JScrollpane( and subclasses ) to acheive this. I would greatly appreciate any sugestions.

    use
    Rectangle rect = MyTable.getVisibleRect();
    Point point = rect.getLocation();
    int firstRow = myTable.rowAtPoint( point ) );
    point.setLocation( rect.getX() + rect.getWidth(),
                             rect.getY() + rect.getHeight() );
    int lastRow = myTable.rowAtPoint( point ) );

  • SQL - Retriving Last 6 rows from Join of 2 Tables

    Hi All
    I want to retrive the last 6 rows from a query which has join of 2 tables
    Thanks in adv.
    Junu

    Hi,
    Check this.
    SELECT e.empno, e.deptno, e.sal,e.rn
    FROM (
         SELECT ROWNUM rn, a.empno, b. deptno, a.sal,
              ( SELECT COUNT(1) FROM scott.emp c, scott.dept d
                        WHERE c.deptno = d.deptno ) max_rn
    FROM scott.emp a, scott.dept b
              WHERE a.deptno = b.deptno
         ) e
    WHERE rn BETWEEN max_rn -6 AND max_rn     
    ORDER BY rn     
    Regards
    K.Rajkumar

Maybe you are looking for