How to compare values for last and second last entry in table?

北城以北 提交于 2020-01-02 05:27:11

问题


I have a table in Oracle called quotes with two columns: date and value.

I would like to compare values for last entry and second last entry in the table.

In this example I would like to get dates for 13.1 and 11.1 in one line and the difference between the values for each date (10-5=5).


Quotes Table:

Date - Value

13.1.2010 - 10

11.1.2010 - 5

10.1.2010 - 2

8.10.2010 - 1


Edit:

I would like to have more complex table with one more column companyId. I need to get items for each company. Table would look like this:

Quotes Table:

Date - Value - CompanyId

13.1.2010 - 10 - 10

11.1.2010 - 5 - 10

10.1.2010 - 2 - 10

8.10.2010 - 1 - 10

12.1.2010 - 7 - 20

10.1.2010 - 3 - 20

9.1.2010 - 2 - 20

8.10.2010 - 2 - 20

I would like to get two lines in this case (but in general just get as many lines as the number of companies are) - one for each company that will return both dates and difference between newest value and second newest value. So in this case it would return:

companyId 10 13.1 and 11.1 and 5 and another line like this:

companyId 20 12.1 and 10.1 and 4 ( 7-3=4).


回答1:


SELECT  *, value - nextvalue AS diff
FROM    (
        SELECT  m.*, LEAD(value) OVER (ORDER BY date DESC) AS nextvalue
        FROM    mytable m
        ORDER BY
                date DESC
        )
WHERE   rownum = 1

Update:

To select results company-wise:

SELECT  value - nextvalue AS diff
FROM    (
        SELECT  m.*,
                LEAD(value) OVER (PARTITION BY companyId ORDER BY date DESC) AS nextvalue,
                ROW_NUMBER() OVER (PARTITION BY companyId ORDER BY date DESC) AS rn
        FROM    mytable m
        )
WHERE   rn = 1


来源:https://stackoverflow.com/questions/2072029/how-to-compare-values-for-last-and-second-last-entry-in-table

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!