You could try something like this. The CTE
ensures the list is unique. The ordering of the string aggregation is handled by WITHIN GROUP (ORDER BY Eid DESC)
.
with unq_cte as (
select *, row_number() over (partition by Vendor order by Eid desc) rn
from (values (1, '67-3M'),
(2, '67-3M'),
(3, '67-3M'),
(4, '799-HD'),
(5, '799-HD'),
(6, '045-FH'),
(7, '045-FH')) tblVendor(Eid, Vendor))
select string_agg(Vendor, ',') within group (order by Eid desc)
from unq_cte
where rn=1;
(No column name)
045-FH,799-HD,67-3M
[Edit] Alternately, you could use SELECT TOP 1 WITH TIES to ensure the vendor list is unique
with unq_cte as (
select top 1 with ties *
from (values (1, '67-3M'),
(2, '67-3M'),
(3, '67-3M'),
(4, '799-HD'),
(5, '799-HD'),
(6, '045-FH'),
(7, '045-FH')) tblVendor(Eid, Vendor)
order by row_number() over (partition by Vendor order by Eid desc))
select string_agg(Vendor, ',') within group (order by Eid desc)
from unq_cte;
[Edit 2] Prior to 2017 you could use STUFF
and FOR XML
to aggregate the string (instead of STRING_AGG
)
with unq_cte as (
select top 1 with ties *
from (values (1, '67-3M'),
(2, '67-3M'),
(3, '67-3M'),
(4, '799-HD'),
(5, '799-HD'),
(6, '045-FH'),
(7, '045-FH')) tblVendor(Eid, Vendor)
order by row_number() over (partition by Vendor order by Eid desc))
select stuff((select ' ' + vendor
from unq_cte
order by Eid desc
for xml path('')), 1, 1, '');