最初のステップは RowNumber
を追加することです 各 PortfolioGroupID の最初の行を識別する列:
SELECT p.PortfolioGroupID,
p.PortfolioGroupCode,
p.DisplayOrder,
p.MemberCode,
m.ContactCode,
m.Custom01,
RowNumber = ROW_NUMBER() OVER(PARTITION BY P.PortfolioGroupID ORDER BY m.ContactCode, p.MemberCode)
FROM [APXFirm].[AdvApp].[vPortfolioGroupMemberFlattened] p
LEFT OUTER JOIN [APXFirm].[AdvApp].[vPortfolioInterestedParty] m
ON p.memberid = m.PortfolioID
WHERE m.ContactCode is not null
AND p.PortfolioGroupCode like '%_Package'
ORDER BY m.ContactCode, p.MemberCode;
次に、3 つの値 (Cover、Sperator、Report) を持つテーブル値コンストラクターで結果セットを結合し、where 句を追加して、最初の行にのみ「Cover」が表示されるようにします。
WITH Data AS
( SELECT p.PortfolioGroupID,
p.PortfolioGroupCode,
p.DisplayOrder,
p.MemberCode,
m.ContactCode,
m.Custom01,
RowNumber = ROW_NUMBER() OVER(PARTITION BY P.PortfolioGroupID ORDER BY p.DisplayOrder)
FROM [APXFirm].[AdvApp].[vPortfolioGroupMemberFlattened] p
LEFT OUTER JOIN [APXFirm].[AdvApp].[vPortfolioInterestedParty] m
ON p.memberid = m.PortfolioID
WHERE m.ContactCode is not null
AND p.PortfolioGroupCode like '%_Package'
)
SELECT d.PortfolioGroupID,
d.PortfolioGroupCode,
d.DisplayOrder,
d.MemberCode,
d.ContactCode,
d.Custom01,
t.PDFType
FROM Data d
CROSS JOIN
( VALUES
('Cover'),
('Seperator'),
('Report')
) t (PDFType)
WHERE d.RowNumber = 1
OR t.PDFType != 'Cover'
ORDER BY ContactCode, MemberCode;