如何比较表中倒数第二个条目的值? [英] How to compare values for last and second last entry in table?

查看:77
本文介绍了如何比较表中倒数第二个条目的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Oracle中有一个名为引号的表,该表有两列: date value .

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.

在此示例中,我想在一行中获取 13.1和11.1 的日期,以及每个日期的值之间的差(10-5 = 5).

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).

行情表:

日期-值

2010年1月13日-10

13.1.2010 - 10

2010年1月11日-5

11.1.2010 - 5

2010年1月10日-2

10.1.2010 - 2

2010年10月8日-1

8.10.2010 - 1

我想拥有一个更复杂的表,其中包含另外一列 companyId .我需要为每个公司获取物品.表格看起来像这样:

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:

行情表:

日期-值-公司ID

2010年1月13日-10-10

13.1.2010 - 10 - 10

2010年1月11日-5-10

11.1.2010 - 5 - 10

2010年1月10日-2-10

10.1.2010 - 2 - 10

2010年10月8日-1-10

8.10.2010 - 1 - 10

2010年1月12日-7-20

12.1.2010 - 7 - 20

2010年1月10日-3-20

10.1.2010 - 3 - 20

9.1.2010-2-20

9.1.2010 - 2 - 20

2010年10月8日-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和11.1和5以及另一行是这样的:

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

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

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

推荐答案

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

更新:

要按公司选择结果,请执行以下操作:

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

这篇关于如何比较表中倒数第二个条目的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆