两个日期之间的重复总和

时间:2015-09-24 07:16:46

标签: sql-server

我正在尝试查找重复项的数量,并在两个特定日期之间将它们相加。但由于分组,无法在having上实施日期标准。

任何帮助将不胜感激。 这就是我试过的

  select AssociationBarcode, 
         count(*) 
    from ContainerInstruction
group by ContainerInstruction.AssociationBarcode
  having count (*) > 1 and 
         AssociationBarcode <> ''
   where CreatedDateTime between getdate() - 1 and getdate()

1 个答案:

答案 0 :(得分:0)

您可以使用内联注释尝试以下查询,其中服务器作为解释:

select 
         AssociationBarcode, 
         count(*) as [count],
         sum(yourColumnWhichNeedsToBeSummed) as [Sum]
      from 
         ContainerInstruction
      -- Note that the Where clause containing dates is applied before grouping. 
      -- This also means that your count and sum will be affected by where clause.
      where 
         CreatedDateTime between getdate() - 1 and getdate() and 
         AssociationBarcode <> ''
      group by 
         ContainerInstruction.AssociationBarcode
      having 
        count (*) > 1 

在此处查看演示小提琴:http://sqlfiddle.com/#!6/bab82/3