TSQL - 对多个值进行子查询过滤

时间:2017-03-27 14:09:08

标签: sql sql-server-2008 tsql duplicates subquery

可以执行返回多个这样的值的子查询来过滤掉重复的值,还是这种子查询无效的语法?

SELECT AccountID, TransID 
FROM CardTrans 
WHERE (AccountID, CardAmount, CardDate) IN (
        SELECT AccountID, CardAmount, CardDate 
        FROM CardTrans 
        GROUP BY AccountID, CardAmount, CardDate 
        HAVING COUNT(*) > 1
    )

我在第3行收到错误说明: 在预期条件的上下文中指定的非布尔类型的表达式,靠近','。

1 个答案:

答案 0 :(得分:4)

SQL Server不支持in的元组。只需使用join

SELECT AccountID, TransID 
FROM CardTrans ct JOIN
     (SELECT AccountID, CardAmount, CardDate 
      FROM CardTrans 
      GROUP BY AccountID, CardAmount, CardDate 
      HAVING COUNT(*) > 1
     ) acc
     ON acc.AccountId = ct.AccountId AND acc.CardAmount = ct.CardAmount AND
        acc.CardDate = ct.CardDate;

等待!我注意到这是同一张桌子。只需使用窗口函数:

select ct.AccountID, ct.TransID 
from (select ct.*,
             count(*) over (partition by AccountID, CardAmount, CardDate) as cnt
      from CardTrans ct
     ) ct
where cnt > 1;