Pierwszym krokiem byłoby dodanie RowNumber
kolumna, aby zidentyfikować pierwszy wiersz dla każdego 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;
Następnie możesz połączyć zestaw wyników z konstruktorem o wartości tabeli z 3 wartościami (Cover, Sperator, Report) i po prostu dodać klauzulę WHERE, aby zapewnić, że „Cover” pojawi się tylko w pierwszym wierszu:
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;