On Top是一个示例数据库。我需要一个查询来显示
请帮忙
GROUP BY CustomerID
Having COUNT(*) >= 1 is not working
答案 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;