首页 > 解决方案 > 当数据字段组合与相同和不同列匹配时选择记录

问题描述

我有一张表,其中包含类似于以下的交易数据:

TransactionID |FirstTType |FirstTDate |SecondTType |SecondTDate |
T1 |A | 01/01/2019 |
T2 |C | 01/02/2019 |
T3 |E | 01/01/2019 |
T4 |D | 02/02/2019 |
T5 |C | 01/02/2019 |
T6 |Z | 01/02/2019 |

从上面的示例中,我在 T2 行中,FirstTType 和 FirstTDate 都具有与 T5 行相同的数据。

我希望得到以下回报

TransactionID |FirstTType |FirstTDate |SecondTType |SecondTDate |
T2 |C | 01/02/2019 |
T5 |C | 01/02/2019 |

我想知道在 SQL Server 中是否有一个好方法可以做到这一点

谢谢

标签: sqlsql-server

解决方案


我想你想要exists

select t.*
from t
where exists (select 1
              from t t2
              where t2.FirstTType = t.FirstTType and
                    t2.FirstTDate = t.FirstTDate and
                    t2.TransactionID <> t.TransactionID
             );

推荐阅读