row_number()
を使用します 関数を実行し、条件を実行します 集計:
select id, IdCust, Ref, max(case when Seq = 1 then stock end) as [Stock A], -- second table *id* max(case when Seq = 1 then code end) as [Code 1], max(case when Seq = 1 then price end) as [Price1], max(case when Seq = 2 then stock end) as [Stock B], -- second table *id* max(case when Seq = 2 then code end) as [Code 2], max(case when Seq = 2 then price end) as [Price2] from (select f.*, s.Id Stock, s.Code, s.Price, row_number() over (partition by f.Ref order by s.id) as Seq from first f inner join second s on s.Ref = f.Ref ) t group by id, IdCust, Ref;
プレ>ただし、これ 知られていると一緒に行くだろう それ以外の場合は dynamic を使用する必要があります そのためのソリューション。