私が以前にこれに対処した方法は、1 行に保持できるアイテムの最大数を計算し、その数の自己結合をデータ テーブルに作成することでした。サンプル データを使用して、任意の ProductID に対して最大 6 つの顧客コードがあるとします。
この SQL は少し見にくいですが、CROSS APPLY をエミュレートするために、一連の自己結合とネストされたクエリを実行して、顧客コードの文字列を作成できます。最大長の文字列をターゲットにすることで、関心のあるレコードのみを保持します。
SELECT Nest4.ProductID,String
FROM (
SELECT ProductID,MaxStringLength
FROM (
SELECT ProductID,max(stringlength) MaxStringLength
FROM (
SELECT ProductID,String,len(String) StringLength
FROM (
SELECT
ProductID
,case when t0.CustomerCode is not null then t0.CustomerCode else '' end
+','+case when t1.CustomerCode is not null then t1.CustomerCode else '' end
+','+case when t2.CustomerCode is not null then t2.CustomerCode else '' end
+','+case when t3.CustomerCode is not null then t3.CustomerCode else '' end
+','+case when t4.CustomerCode is not null then t4.CustomerCode else '' end
+','+case when t5.CustomerCode is not null then t5.CustomerCode else '' end
"String"
FROM MyTable t0
LEFT JOIN MyTable t1 on t0.ProductID=t1.ProductID and t0.CustomerCode<t1.CustomerCode
LEFT JOIN MyTable t2 on t0.ProductID=t2.ProductID and t1.CustomerCode<t2.CustomerCode
LEFT JOIN MyTable t3 on t0.ProductID=t3.ProductID and t2.CustomerCode<t3.CustomerCode
LEFT JOIN MyTable t4 on t0.ProductID=t4.ProductID and t3.CustomerCode<t4.CustomerCode
LEFT JOIN MyTable t5 on t0.ProductID=t5.ProductID and t4.CustomerCode<t5.CustomerCode
) AS Nest1
) AS Nest2 GROUP BY ProductID
) Nest3
) Nest4
JOIN (
SELECT ProductID,String,len(String) StringLength
FROM (
SELECT
t0.ProductID ProductID
,case when t0.CustomerCode is not null then t0.CustomerCode else '' end
+','+case when t1.CustomerCode is not null then t1.CustomerCode else '' end
+','+case when t2.CustomerCode is not null then t2.CustomerCode else '' end
+','+case when t3.CustomerCode is not null then t3.CustomerCode else '' end
+','+case when t4.CustomerCode is not null then t4.CustomerCode else '' end
+','+case when t5.CustomerCode is not null then t5.CustomerCode else '' end
"String"
FROM MyTable s
LEFT JOIN MyTable t1 on t0.ProductID=t1.ProductID and t0.CustomerCode<t1.CustomerCode
LEFT JOIN MyTable t2 on t0.ProductID=t2.ProductID and t1.CustomerCode<t2.CustomerCode
LEFT JOIN MyTable t3 on t0.ProductID=t3.ProductID and t2.CustomerCode<t3.CustomerCode
LEFT JOIN MyTable t4 on t0.ProductID=t4.ProductID and t3.CustomerCode<t4.CustomerCode
LEFT JOIN MyTable t5 on t0.ProductID=t5.ProductID and t4.CustomerCode<t5.CustomerCode
) AS Nest1
) V2
ON Nest4.ProductID=V2.ProductID and Nest4.MaxStringLength=V2.StringLength