I'm using SQL Server 2014.
I'd like the following to give me no duplicate phone ID's or numbers:
WITH Phones as
(
SELECT * FROM (VALUES
(1,'602 600 8000'),
(2,'602 600 8001'),
(3,'602 600 8002')
) AS Vict_t (Id,Number)
), InvoicePhones as
(
SELECT * FROM (VALUES
(10, 1, 100, 'Alpha'),
(11, 1, 101, 'Bravo'),
(12, 1, 102, 'Charlie'),
(13, 2, 103, 'Alpha'),
(14, 2, 104, 'Bravo'),
(15, 2, 105, 'Charlie'),
(16, 3, 106, 'Alpha'),
(17, 3, 107, 'Bravo'),
(18, 3, 108, 'Charlie')
) as ip_t (Id,PhoneId,VoiceId, Name)
), Voices as
(
SELECT * FROM (VALUES
(100, '201701'),
(101, '201702'),
(102, '201703'),
(103, '201704'),
(104, '201705'),
(105, '201706'),
(106, '201708'),
(107, '201709'),
(108, '201710')
) AS Voices_t (Id,BillingCycle)
)
SELECT P.Id PhoneId, P.Number, IP.Name
FROM Phones P
LEFT JOIN InvoicePhones IP on IP.PhoneId = P.Id and IP.VoiceId =
(
select TOP 1 id
from Voices V
where V.Id = IP.VoiceId
order by V.BillingCycle desc
)
I cannot understand why the sub-select is not eliminating the duplicates.
What I'm receiving is this:
1 602 600 8000 Alpha
1 602 600 8000 Bravo
1 602 600 8000 Charlie
2 602 600 8001 Alpha
2 602 600 8001 Bravo
2 602 600 8001 Charlie
3 602 600 8002 Alpha
3 602 600 8002 Bravo
3 602 600 8002 Charlie
What I'm expecting is this:
1 602 600 8000 Charlie
2 602 600 8001 Charlie
3 602 600 8002 Charlie
This example uses simple integer ID's, but the real tables I'm working with are using uniqueidentifier. Thus the answer I need must take that into account.
I tried both versions of this accepted answer, but it doesn't work for me.
What am I missing?
Update
In addition to the answer I chose, I realized another way to solve this problem is as follows:
SELECT P.Id PhoneId, P.Number, IP.Name
FROM Phones P
LEFT JOIN InvoicePhones IP on IP.PhoneId = P.Id and IP.VoiceId =
(
select TOP 1 V.Id
from Voices V
INNER JOIN InvoicePhones IPS ON IPS.VoiceId = V.Id
WHERE P.Id = IPS.PhoneId
order by V.BillingCycle desc
)
I'm curious if they can also be solved with an OUTER APPLY, as mentioned in this other SO post