SQL Server:比较行,当某些值相同时从结果中排除

时间:2016-03-05 02:03:25

标签: sql compare rows

我有以下SQL Server查询问题。

如果在另一行中有一行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

结果应该是:

ID      ISSUE_DATE                  MATURITY_DATE           AMOUNT_USD
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
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
1       2015-01-12 00:00:00.000     2018-01-12 00:00:00.000     18000

我试过自我加入,但是我得不到正确的结果。

提前致谢!

2 个答案:

答案 0 :(得分:0)

你可以试试这样的东西吗? '不存在'这样做的方式。

select * from table t1 where not exists (select 'x' from table t2 where t1.issue_date = t2.maturity_date and t1.amount_usd=t2.amount_usd and t1.id = t2.id)

答案 1 :(得分:0)

我考虑制作所有欺骗的子查询,然后从第一个表中删除它们,如下所示:

       <Button
        android:id="@+id/btn_first"
        android:layout_above="@+id/btn_second"
        android:text="ONE"
        />
       <Button
        android:id="@id/btn_second"
        android:text="TWO"
        />