2016-01-23 131 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'子句。 –