WHERE条件基于另一个查询中的count行

时间:2014-05-15 21:11:52

标签: sql-server

我正在尝试使用基于另一个查询中获得的行的行的条件进行查询。但我无法得到正确的方法。有什么身体可以帮助我吗?我想做的是:

SELECT    ChildDummyTable.Id ChildDummyTableId,    
ParentDummyTable.Id ParentDummyTableId
FROM    [DummyTable]   ChildDummyTable
 INNER JOIN [DummyTable] ParentDummyTable 
     ON ParentDummyTable.Id = ChildDummyTable.ParentDummyRowId 
     where (SELECT DummyRow2 FROM DummyTable2 WHERE DummyTableId=ChildDummyTable.Id
        except SELECT DummyRow2 FROM DummyTable2 ParentDummyTable2
         WHERE ParentDummyTable2.DummyTableId=DummyTable.Id).COUNT(DummyRow2)>0

2 个答案:

答案 0 :(得分:2)

您可以使用EXISTS

SELECT  ChildDummyTable.Id ChildDummyTableId,    
        ParentDummyTable.Id ParentDummyTableId
FROM [DummyTable] ChildDummyTable
INNER JOIN [DummyTable] ParentDummyTable 
    ON ParentDummyTable.Id = ChildDummyTable.ParentDummyRowId 
WHERE EXISTS(SELECT DummyRow2 FROM DummyTable2 
             WHERE DummyTableId=ChildDummyTable.Id
             EXCEPT 
             SELECT DummyRow2 FROM DummyTable2 ParentDummyTable2
             WHERE ParentDummyTable2.DummyTableId=DummyTable.Id)

答案 1 :(得分:1)

with a as
(SELECT ChildDummyTable.Id ChildDummyTableId
    ,ParentDummyTable.Id ParentDummyTableId
    ,ROW_NUMBER() OVER(PARTITION by 
                ChildDummyTable.Id ChildDummyTableId
        ,ParentDummyTable.Id ParentDummyTableId 
) 
aS duplicateRecCount

FROM    [DummyTable]   ChildDummyTable
  INNER JOIN [DummyTable] ParentDummyTable 
     ON ParentDummyTable.Id = ChildDummyTable.ParentDummyRowId 
)

Select * from a 
where duplicateRecCount > 1