2016-01-23 94 views
-1

enter image description here只选择重复

最上面是一个示例数据库。我需要查询来显示

  1. 过滤一次进行多个项目的客户。
  2. 删除当前没有正在进行项目的客户的记录(过去项目的记录应该删除)。

请帮

GROUP BY CustomerID 
Having COUNT(*) >= 1 is not working 

回答

2

对于重复出现是不同的工艺,例如,你可以使用窗口函数:

;with cte as (
    select *, count(*) over(partition by customerID) as cnt 
    from <Table> 
) 
select * 
from cte 
where 
    cnt > 1 
+0

感谢罗马。那是完整的代码吗? –

+0

这工作,并非常感谢它! –

2

,仅保留最近的项目,使用row_number()

with t as (
    select t.*, 
      row_number() over (partition by customerid order by enddate desc) as seqnum 
    from table t 
    ) 
select t.* 
from t 
where seqnum > 1; 

致力于LLY从数据库中删除旧的记录,你可以使用一个类似的结构:

with todelete as (
    select t.*, 
      row_number() over (partition by customerid order by enddate desc) as seqnum 
    from table t 
    ) 
delete from todelete 
where seqnum = 1; 

不过,如果你只是想在客户没有正在进行proejct:

select customerid 
from table t 
group by customerid 
having sum(case when getdate() between startdate and endate then 1 else 0 end) = 0; 
+0

第二个查询中有错字。应删除从删除 其中seqnum> 1' –

+0

@戈登感谢代码set.about删除代码我们如何指定日期?例如:删除比指定日期早的项目。 –

+1

@ShazminA。 。 。你只需要使用'where'子句。 –