仅选择重复

时间:2016-01-23 11:50:45

标签: sql sql-server sql-server-2008

enter image description here

On Top是一个示例数据库。我需要一个查询来显示

  1. 过滤一次持续制作多个项目的客户。
  2. 删除当前没有正在进行的项目的任何客户的记录(应删除过去项目的记录)。
  3. 请帮忙

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

2 个答案:

答案 0 :(得分:1)

对于重复项,有不同的技术,例如,您可以使用窗口功能:

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

答案 1 :(得分:1)

要仅获取最新项目,请使用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;

要从数据库中实际删除旧记录,可以使用类似的构造:

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;

但是,如果您只是希望客户没有正在进行的项目:

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