SQL - 按ID,日期和金额比较行

时间:2015-12-31 07:01:18

标签: sql compare rows

我需要SELECT一行中issue_date = maturity_date的另一行id,且相同的amount_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

提前致谢!

1 个答案:

答案 0 :(得分:0)

请执行以下操作: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 |