ON
句に複雑な条件を含めることができます。aを使用するLEFT OUTER JOIN
と、句の奇数の場合(TX37)を処理できますWHERE
。
R
節内のへの参照WHERE
は、外部結合が内部結合に変換されないようにNULLを処理する必要があることに注意してください。
select L.*
from dbo.Orders as L left outer join
dbo.Orders as R on R.OrderId = L.OrderId and (
( L.Code = 'TX33' and R.Code = 'TX34' ) or
( L.Code = 'TX35' and R.Code = 'TX36' ) or
( L.Code = 'TX38' and R.Code = 'TX39' ) )
where L.PurchaseDate is not NULL and ( L.Code = 'TX37' or R.Code is not NULL )
TX33、TX34 、およびその他のパターンの1つ以上を含む注文のみが本当に必要な場合は、もう少し複雑です。とを使用group by L.OrderId
するとcount( L.OrderId )
、たとえば、パターン間で2つ以上一致する注文を見つけることができます。それは次のようなものに近づき始めます:
declare @Orders as Table ( Id Int Identity, OrderId Int, Code VarChar(4), PurchaseDate Date )
insert into @Orders ( OrderId, Code, PurchaseDate ) values
( 1, 'TX37', GetDate() ),
( 2, 'TX37', GetDate() ), ( 2, 'FOO', GetDate() ),
( 3, 'TX33', GetDate() ), ( 3, 'TX34', GetDate() ),
( 4, 'TX33', GetDate() ), ( 4, 'TX34', GetDate() ), ( 4, 'TX37', GetDate() ),
( 5, 'TX33', GetDate() ), ( 5, 'TX34', GetDate() ), ( 5, 'TX35', GetDate() ),
( 5, 'TX36', GetDate() ),
( 6, 'TX33', GetDate() ), ( 6, 'TX34', GetDate() ), ( 6, 'TX35', GetDate() ),
( 6, 'TX36', GetDate() ), ( 6, 'TX37', GetDate() ),
( 7, 'TX38', GetDate() ), ( 7, 'TX39', GetDate() ), ( 7, 'TX35', GetDate() ),
( 7, 'TX36', GetDate() ), ( 7, 'TX37', GetDate() )
select * from (
select L.OrderId,
Max( case when L.Code = 'TX33' and R.Code = 'TX34' then 1 else 0 end ) as Mandatory,
Count( L.OrderId ) as Matches
from @Orders as L left outer join
@Orders as R on R.OrderId = L.OrderId and (
( L.Code = 'TX33' and R.Code = 'TX34' ) or
( L.Code = 'TX35' and R.Code = 'TX36' ) or
( L.Code = 'TX38' and R.Code = 'TX39' ) )
where L.PurchaseDate is not NULL and ( L.Code = 'TX37' or R.Code is not NULL )
group by L.OrderId ) as Arnold
where Mandatory = 1 and Matches > 1