サービス会社とさまざまな契約を結んでいる顧客のリストがあります。
表は次のとおりです。
idCustomer idContract NameCust
-----------------------------------------
1 A Karen
1 B Will
2 A Karen
2 B Will
3 C Steph
4 C Peter
しかし、カレンとウィルは複数の契約を結ぶことができるので、私は彼らと他の顧客グループのために一意のIDが必要です。私が欲しい結果テーブル:
idCustomer idContract NameCust Customer_GroupID
-----------------------------------------------------
1 A Karen 1
1 B Will 1
2 A Karen 1
2 B Will 1
3 C Steph 2
4 C Peter 2
必要な結果が得られないさまざまなことを試したため、行き詰まりました。フォーラムでDense_Rank関数を使用した人を見つけましたが、結果は次のとおりです。
SELECT
RANK() OVER (ORDER BY idCustomers) AS Customer_GroupID,
IdCustomers,
IdContract
FROM
Table
結果は次のとおりです。
Cust_GroupID idCustomer idContract
--------------------------------------
1 1 A
2 1 B
1 2 A
2 2 B
3 3 C
3 4 C
複数のselectを使用しようとしましたが、存在しませんが何もありません。
私はあなたの要件を理解したようです。それでも、すべての人に完全に明確にするために、もう少しサンプルデータをスローする必要があります。既存のサンプルデータにさらにいくつかの多様なサンプルデータを追加します。
さまざまなサンプルデータでテストし、機能しない場合はお知らせください。
サンプルデータ、
create table #test(idCustomer int,idContract varchar(50) , NameCust varchar(50))
insert into #test (idCustomer ,idContract , NameCust ) VALUES
(1,'A','Karen')
,(1,'B','Will' )
,(2,'A','Karen')
,(2,'B','Will' )
,(3,'C','Steph')
,(4,'C','Peter')
;with CTE as
(
select *
,ROW_NUMBER()over(order by idCustomer)rn
from #test
)
,CTE1 as
(
select t.id,t.idContract,t.NameCust
, isnull(t1.idCustomer,t.idCustomer)customerGroupID
from CTE t
outer apply(
select top 1 idCustomer
from CTE t1
where t1.id< t.id
and((t.idCustomer=t1.idCustomer)
or (t.idContract=t1.idContract))
order by t1.id
)t1
)
,CTE2 AS(
select *
,DENSE_RANK()OVER( order by customerGroupID )Customer_GroupID
from CTE1
)
select * from CTE2
create table #test1(id int identity(1,1),idCustomer int
,idContract varchar(50) , NameCust varchar(50),customer_Groupid int)
insert into #test1 (idCustomer ,idContract
, NameCust,customer_Groupid )
select idCustomer ,idContract , NameCust,null
from #test
DECLARE @idCustomer INT
DECLARE @idContract varchar(50)
DECLARE @id INT
declare @customer_Groupid int
DECLARE @getCustomer CURSOR
SET @getCustomer = CURSOR FOR
SELECT id, idCustomer,idContract
FROM #test1
OPEN @getCustomer
FETCH NEXT
FROM @getCustomer INTO @id, @idCustomer,@idContract
WHILE @@FETCH_STATUS = 0
BEGIN
select top 1 @customer_Groupid=customer_Groupid
from #test1 where id<@id order by id desc
if not exists(select 1 from #test1 where id<@id
and (idCustomer=@idCustomer or idContract=@idContract))
BEGIN
select top 1 @customer_Groupid=customer_Groupid
from #test1 where id<@id order by id desc
if(@customer_Groupid is not null)
set @customer_Groupid=@customer_Groupid+1
end
if(@customer_Groupid is null)
set @customer_Groupid=1
update #test1 set customer_Groupid=@customer_Groupid where id=@id
FETCH NEXT
FROM @getCustomer INTO @id, @idCustomer,@idContract
END
CLOSE @getCustomer
DEALLOCATE @getCustomer
select * from #test1
drop table #test1
drop table #test
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加