SQL Server查找具有相同ID的重复日期

时间:2013-06-27 14:11:13

标签: sql sql-server-2005

我正在使用SQL Server 2005,我有一个包含以下内容的表...

[uniqueID] [requirementId] [number] [description] [dtmexecuted] [amount]

我需要找到具有相同requirementid和dtmexecuted的所有行。我试过了

select 
    requirementid, dtmexecuted, count(*) 
from 
    [MyTable]
group by 
    requirementid, dtmexecuted
having 
    count(*) > 1
order by 
    requirementid

但这并没有让我得到我需要的结果。这是我需要的一个例子。

[FEE55DE4-F7AD-438F-83F5-0002C7DAF993] [3719D29C-8532-4128-BECA-F720106AE61B] [03] [desc] [2011-04-01 00:00:00.000] [900.00]

[BRW46DE4-F1GC-125C-51RC-3985G7CFF873] [3719D29C-8532-4128-BECA-F720106AE61B] [04] [desc 2] [2011-04-01 00:00:00.000] [1900.00]

我需要写一些东西,将这两行归还为具有相同的requirementid和dtmexecuted。

2 个答案:

答案 0 :(得分:4)

如果需要返回行,则需要使用窗口函数:

select [uniqueID], [requirementId], [number], [description], [dtmexecuted], [amount]
from (select t.*,
             count(*) over (partition by requirementid, dtmexecuted) as cnt
      from MyTable t
     ) t
where cnt > 1

答案 1 :(得分:0)

这是我解决这个问题的常用方法。

select
  dest.*
from
  (
  select 
    requirementid,
    dtmexecuted,
    count(*) as RowCount
  from [MyTable]
  group by requirementid, dtmexecuted
  having count(*) > 1
  ) sub
  join [MyTable] dest 
    on dest.requirementid = sub.requirementid
    and dest.dtmexecuted = sub.dtmexecuted
order by requirementid, dtmexecuted

你可以CTE或Table变量来做这件事......