最上面是一個示例數據庫。我需要查詢來顯示
- 過濾一次進行多個項目的客戶。
- 刪除當前沒有正在進行項目的客戶的記錄(過去項目的記錄應該刪除)。
請幫
GROUP BY CustomerID
Having COUNT(*) >= 1 is not working
最上面是一個示例數據庫。我需要查詢來顯示
請幫
GROUP BY CustomerID
Having COUNT(*) >= 1 is not working
對於重複出現是不同的工藝,例如,你可以使用窗口函數:
;with cte as (
select *, count(*) over(partition by customerID) as cnt
from <Table>
)
select *
from cte
where
cnt > 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;
致力於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;
第二個查詢中有錯字。應刪除從刪除 其中seqnum> 1' –
@戈登感謝代碼set.about刪除代碼我們如何指定日期?例如:刪除比指定日期早的項目。 –
@ShazminA。 。 。你只需要使用'where'子句。 –
感謝羅馬。那是完整的代碼嗎? –
這工作,並非常感謝它! –