Il primo passo sarebbe aggiungere un RowNumber
colonna per identificare la prima riga per ogni PorfoilioGroupID:
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;
Quindi puoi unire i tuoi risultati impostati con un costruttore con valori di tabella con i tuoi 3 valori (Cover, Sperator, Report) e aggiungere semplicemente una clausola where per assicurarti che 'Cover' appaia solo per la prima riga:
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;