Det første skridt ville være at tilføje et RowNumber
kolonne for at identificere den første række for hvert 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;
Derefter kan du kombinere dit resultatsæt med en tabelvurderet konstruktør med dine 3 værdier (Cover, Sperator, Report), og blot tilføje en where-klausul for at sikre, at 'Cover' kun vises for den første række:
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;