选择在某些列上重复的记录

时间:2019-01-25 16:30:25

标签: sql sql-server

我有以下数据:-

LogID     Tstamp                   eCode   eOrder
14281889  2019-01-04 08:14:52.000  120     0
14281890  2019-01-04 08:14:52.000  120     0
14281891  2019-01-04 08:14:52.000  132     2
14281892  2019-01-04 08:14:52.000  133     3
14281893  2019-01-04 08:14:52.000  10      4
14281894  2019-01-04 08:15:02.000  70      0

我需要选择由TstampeCodeeOrder复制的记录,并带回所有匹配的记录。

例如选择将返回

LogID     Tstamp                   eCode   eOrder
14281889  2019-01-04 08:14:52.000  120     0
14281890  2019-01-04 08:14:52.000  120     0

5 个答案:

答案 0 :(得分:5)

最简单的方法是使用CTE进行计数:

WITH CTE AS(
    SELECT LogID, TStamp, eCode, eOrder,
           COUNT(LogID) OVER (PARTITION BY TStamp, eCode, eOrder) AS DupeCount
    FROM {YourTable}) --Replace {TableName} with appropriate table name.
SELECT LogID, TStamp, eCode, eOrder
FROM CTE
WHERE DupeCount > 1;

答案 1 :(得分:2)

使用exists获取公仔:

select * from tablename t
where exists (
  select 1 from tablename tt
  where tt.Tstamp = t.Tstamp and tt.eCode = t.eCode and tt.eOrder = t.eOrder and tt.LogID <> t.LogID 
)

答案 2 :(得分:0)

select
   LogID,
   Tstamp,
   eCode,
   eOrder 
from
   XXX 
where
   Tstamp + '/' + eCode + '/' + eOrder in 
   (
      select
         Tstamp + '/' + eCode + '/' + eOrder 
      from
         XXX 
      group by
         Tstamp + '/' + eCode + '/' + eOrder 
      having
         count(*) > 1
   )
;

答案 3 :(得分:0)

使用where exists和一些测试代码:

create table #testtbl (
    LogID int,
    Tstamp datetime,
    eCode tinyint,
    eorder tinyint
);

insert into #testtbl
values 
(14281889, '2019-01-04 08:14:52.000', 120, 0),
(14281890, '2019-01-04 08:14:52.000', 120, 0),
(14281891, '2019-01-04 08:14:52.000', 132, 2),
(14281892, '2019-01-04 08:14:52.000', 133, 3),
(14281893, '2019-01-04 08:14:52.000', 10, 4),
(14281894, '2019-01-04 08:15:02.000', 70, 0);

select *
from #testtbl t
where exists (
    select *
    from #testtbl
    where Tstamp = t.Tstamp
    and eCode = t.eCode
    and eorder = t.eOrder
    and LogID <> t.LogID
);

答案 4 :(得分:0)

这是使用WITH TIES子句的另一种选择,并且对结果sign()有点乐趣。

Select Top 1 with ties *
 From  YourTable
 Order By sign(sum(1) over (Partition By Tstamp,eCode,eorder)-1) desc

返回

LogID       Tstamp                  eCode   eorder
14281889    2019-01-04 08:14:52.000 120     0
14281890    2019-01-04 08:14:52.000 120     0