如何仅查询在我的表格中出现两次的记录?
目前我的表看起来像这样:
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 )
答案 0 :(得分:2)
不应该这样做:
select *
from table1
where (RecordT, ReadLoc) in
(select RecordT, ReadLoc
from table1
group by RecordT, ReadLoc
having count(*) > 1)
答案 1 :(得分:2)
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
答案 2 :(得分: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' */