【问题标题】:SQL - Compare rows by id, date and amountSQL - 按 id、日期和金额比较行
【发布时间】:2015-12-31 07:01:17
【问题描述】:

我需要SELECT 一行,其中issue_date = maturity_date 的另一行具有相同的id 和相同的金额_usd。

我尝试了自我加入,但我没有得到正确的结果。

这是我的表格的简化版本:

ID       ISSUE_DATE                     MATURITY_DATE        AMOUNT_USD
1       2010-01-01 00:00:00.000     2015-12-01 00:00:00.000     5000
1       2010-01-01 00:00:00.000     2001-09-19 00:00:00.000     700
2       2014-04-09 00:00:00.000     2019-04-09 00:00:00.000     400
1       2015-12-01 00:00:00.000     2016-12-31 00:00:00.000     5000
5       2015-02-24 00:00:00.000     2015-02-24 00:00:00.000     8000
4       2012-11-29 00:00:00.000     2015-11-29 00:00:00.000     10000
3       2015-01-21 00:00:00.000     2018-01-21 00:00:00.000     17500
2       2015-02-02 00:00:00.000     2015-12-05 00:00:00.000     12000
1       2015-01-12 00:00:00.000     2018-01-12 00:00:00.000     18000
2       2015-12-05 00:00:00.000     2016-01-10 00:00:00.000     12000

Result should be:

ID      ISSUE_DATE                         MATURITY_DATE        AMOUNT_USD
1       2015-12-01 00:00:00.000     2016-12-31 00:00:00.000     5000
2       2015-12-05 00:00:00.000     2016-01-10 00:00:00.000     12000

提前致谢!

【问题讨论】:

    标签: sql compare rows


    【解决方案1】:

    执行以下操作:http://sqlfiddle.com/#!6/c0a02/1

    select a.id, a.issue_date, a.maturity_date, a.amount_usd
    from tbl a
    inner join tbl b
        on a.id = b.id
        and a.maturity_date = b.issue_date
    
        -- added to prevent same maturity date and issue date
    where a.maturity_date <> a.issue_date
    

    输出:

    | id |                 issue_date |              maturity_date | amount_usd |
    |----|----------------------------|----------------------------|------------|
    |  1 |  January, 01 2010 00:00:00 | December, 01 2015 00:00:00 |       5000 |
    |  2 | February, 02 2015 00:00:00 | December, 05 2015 00:00:00 |      12000 |
    

    【讨论】:

    • 谢谢,这对我很有帮助,但我还是有问题。真实表中有很多数据,在某些情况下,当我在同一行 issue_date =maturity_date 时,它​​也会返回该行。我编辑了 ID 5 来向您展示我的意思,它还返回行 whit id 5,这是我不想要的。你能帮我解决这个问题吗?
    • 添加了这个:where a.maturity_date &lt;&gt; a.issue_date