1

如何只查询在我的表中出现两次的记录?

目前我的桌子看起来像这样:

Number   Date                  RecordT     ReadLoc
123      08/13/13 1:00pm       N           Gone
123      08/13/13 2:00pm       P           Home
123      08/13/13 3:00pm       N           Away
123      08/13/13 4:00pm       N           Away

我需要一个查询来选择在 RecordT 字段中具有相同“值”和在 ReadLoc 字段中具有相同“值”的记录。

因此,我的上述结果将显示在查询中:

Number   Date                  RecordT     ReadLoc
123      08/13/13 3:00pm       N           Away
123      08/13/13 4:00pm       N           Away

我试图做一个这样的子选择:

SELECT t.Number, t.Date, n.RecordT, n.ReadLoc
FROM Table1 t join Table2 n ON t.Number = n.Number
WHERE t.Number IN (SELECT t.Number FROM Table1 GROUP BY t.Number HAVING COUNT(t.Number) > 1 )
AND n.ReadLoc IN (SELECT n.ReadLoc FROM Table2 GROUP n.ReadLoc HAVING COUNT(n.ReadLoc) > 1 )
4

3 回答 3

3
SELECT a.*
FROM Table1 a
JOIN (SELECT RecordT, ReadLoc
      FROM Table1
      GROUP BY RecordT, ReadLoc
      HAVING COUNT(*) > 1
      )b
ON a.RecordT = b.RecordT
 AND a.ReadLoc = b.ReadLoc

SQL小提琴

于 2013-08-15T20:31:36.583 回答
2

这不应该工作:

select * 
from table1 
where (RecordT, ReadLoc) in 
   (select RecordT, ReadLoc 
    from table1 
    group by RecordT, ReadLoc 
    having count(*) > 1)
于 2013-08-15T20:25:04.593 回答
1

以下内容可以作为基础:

;with cte as (
    select *, cnt = count(1) over (partition by RecordT, ReadLoc)
    from TableName
)
select *
from cte
where cnt > 1

如果您TableName实际上是两个连接表的视图,请尝试:

;with TableName as (
    SELECT t.Number, t.Date, n.RecordT, n.ReadLoc
    FROM Table1 t
        join Table2 n ON t.Number = n.Number
),
cte as (
    select Number, Date, RecordT, ReadLoc,
        cnt = count(1) over (partition by RecordT, ReadLoc)
    from TableName
)
select Number, Date, RecordT, ReadLoc
from cte
where cnt > 1 /* and RecordT='N' and ReadLoc='AWAY' */
于 2013-08-15T20:21:23.947 回答