CTE to find duplicates? - sql

Can someone show me how i would add to this CTE to include the column 'Address Type ' that is stored in another table called 'WeccoPartyAddress'?
I am trying to find duplicates for the first and last name, and mailing address where Address Type address = 'Mailing'
with dups as (
select
wp.GtId
from CORE.WeccoParty wp
where exists (select 1
from CORE.WeccoParty wpe
where wp.FirstName = wpe.FirstName
and wp.LastName = wpe.LastName
and wp.Dob = wpe.Dob
and wp.GtId <> wpe.GtId
)
)
select distinct
wp.GtId,
wp.CrmPartyId,
wp.LegalName,
wp.BusinessClass,
wp.RmFullName,
wp.PbeFullName,
wp.OverallClientStatus,
wp.OverallRpStatus,
wp.FirstName + ' ' + wp.LastName FullName,
wp.Dob
from CORE.WeccoParty wp
join dups d on d.GtId = wp.GtId
order by 9,1

Consider extending your CTE by adding a JOIN clause in outer and subquery to the WeccoPartyAddress table with needed WHERE clauses. Notice too the distinct added to avoid repeated IDs for possible one-to-many relationship between the tables.
with dups as (
select distinct p.GtId
from CORE.WeccoParty p
join CORE.WeccoPartyAddress a ON p.GtId = a.GtId
where exists (select 1
from CORE.WeccoParty sub_p
left join CORE.WeccoPartyAddress sub_a
on sub_p.GtId = sub_a.GtId and sub_a.AddressType = 'Mailing'
where (p.FirstName = sub_p.FirstName
and p.LastName = sub_p.LastName
and p.Dob = sub_p.Dob
and p.GtId <> sub_p.GtId)
and a.MailingAddress = sub_a.MailingAddress
and a.GtId <> sub_a.GtId
)
)
And depending on data and relationships (e.g., can GtId have same bio details AND/OR same mailing address?) which you would know more, you may need to adjust above query. These may involve swapping left join to join and/or the WHERE conditions such as:
where (p.FirstName = sub_p.FirstName
and p.LastName = sub_p.LastName
and p.Dob = sub_p.Dob
and p.GtId <> sub_p.GtId)
or
(a.MailingAddress = sub_a.MailingAddress
and a.GtId <> sub_a.GtId)

Related

Multiple strings containing duplicates

I am required to do the following :
The Address should be concatenated into a lower case string with no
spaces and then compared against the other address.
I have the below sql - with no schema this will be hard to answer but I really just want to know how I can add in the part to concat the address into lower case with no spaces and then compare against other addresses.
I have the following fields along with what's already in the SQL below: Address1, Address2, Address3, Town, Postcode.
;With dups as (
select distinct p.GtId
from CORE.WeccoParty p
join CORE.WeccoPartyAddress a ON p.GtId = a.GtId
where exists (select 1
from CORE.WeccoParty sub_p
left join CORE.WeccoPartyAddress sub_a
on sub_p.GtId = sub_a.GtId and sub_a.AddressType = 'Mailing'
where (p.FirstName = sub_p.FirstName
and p.LastName = sub_p.LastName
and p.Dob = sub_p.Dob
and p.GtId <> sub_p.GtId)
and a.MailingAddress = sub_a.MailingAddress
and a.GtId <> sub_a.GtId
)
)

Progress SQL Column cannot be found or is not specified for query

I'm writing SQL against a Progress 10.2B07 database and am getting the following error "Column 'OUTERINVOICEHEADER.MEMBERID' cannot be found or is not specified for query (13865).
Here is the query:
select concat(substring(OuterInvoiceHeader.sold_to_cust_nbr, 1, 6) + '-', OuterInvoiceHeader.sold_to_cust_seq) as MemberID,
sum(OuterInvoiceHeader.net_weight) as TotalInvoicePounds,
sum(OuterInvoiceHeader.net_weight / 2000) as TotalTons,
sum(OuterInvoiceHeader.invoice_amt) as InvoiceAmount,
sum(InvoiceSurcharges.Surcharge) as Surcharges,
sum(OuterInvoiceHeader.invoice_amt - InvoiceSurcharges.Surcharge) as Total,
sum(Returns.qty_received) as PoundsReturned
from AXS.PUB.ivc_header OuterInvoiceHeader
inner join
(select m.invoice_nbr, sum(m.extension) Surcharge from AXS.PUB.ivc_mchgs m
inner join
AXS.PUB.ivc_header h
on h.invoice_nbr = m.invoice_nbr
group by m.invoice_nbr) InvoiceSurcharges
on OuterInvoiceHeader.invoice_nbr = InvoiceSurcharges.invoice_nbr
left outer join
(select concat(substring(ReturnHeader.ship_to_nbr, 1, 6)+'-',InnerInvoiceHeader.sold_to_cust_seq) as ReturnMemberID,
ReturnHeader.invoice_nbr as ReturnInvoiceNum,
qty_received
from AXS.PUB.return_hdr ReturnHeader
inner join
AXS.PUB.ivc_header InnerInvoiceHeader
on ReturnHeader.invoice_nbr = InnerInvoiceHeader.invoice_nbr
inner join AXS.PUB.return_line ReturnLine
on ReturnHeader.claim_nbr = ReturnLine.claim_nbr
where ReturnInvoiceNum = '0001010914'
group by ReturnMemberID, ReturnInvoiceNum, qty_received) Returns
on OuterInvoiceHeader.MemberID = Returns.ReturnMemberID
--on OuterInvoiceHeader.invoice_nbr = Returns.ReturnInvoiceNum
where OuterInvoiceHeader.sold_to_cust_nbr = '000837' and OuterInvoiceHeader.invoice_date between '06/01/2016' and '06/30/2016' and OuterInvoiceHeader.invoice_status = '5804' and OuterInvoiceHeader.invoice_type='5601'
group by MemberID
The problem is in the left join; the commented out on clause "on OuterInvoiceHeader.invoice_nbr = Returns.ReturnInvoiceNum" will work if uncommented. The "on OuterInvoiceHeader.MemberID = Returns.ReturnMemberID" clause gives me the error.
What I don't understand is that both of these reference a column in the top SELECT statement, the only difference is that one is a concatenation and the other is not.
I hope that I just can't see the forest for the trees here and the answer is simple, so if anyone has any suggestions or questions I'm all ears.
try this:
I replaced the references to the alias MemberID to be the actual concatinated columns CONCAT(SUBSTRING(OuterInvoiceHeader.sold_to_cust_nbr, 1, 6)+'-', OuterInvoiceHeader.sold_to_cust_seq)
SELECT CONCAT(SUBSTRING(OuterInvoiceHeader.sold_to_cust_nbr, 1, 6)+'-', OuterInvoiceHeader.sold_to_cust_seq) AS MemberID
, SUM(OuterInvoiceHeader.net_weight) AS TotalInvoicePounds
, SUM(OuterInvoiceHeader.net_weight / 2000) AS TotalTons
, SUM(OuterInvoiceHeader.invoice_amt) AS InvoiceAmount
, SUM(InvoiceSurcharges.Surcharge) AS Surcharges
, SUM(OuterInvoiceHeader.invoice_amt - InvoiceSurcharges.Surcharge) AS Total
, SUM(Returns.qty_received) AS PoundsReturned
FROM AXS.PUB.ivc_header OuterInvoiceHeader
INNER JOIN
(SELECT m.invoice_nbr
, SUM(m.extension) Surcharge
FROM AXS.PUB.ivc_mchgs m
INNER JOIN AXS.PUB.ivc_header h ON h.invoice_nbr = m.invoice_nbr
GROUP BY m.invoice_nbr) InvoiceSurcharges ON OuterInvoiceHeader.invoice_nbr = InvoiceSurcharges.invoice_nbr
LEFT OUTER JOIN
(SELECT CONCAT(SUBSTRING(ReturnHeader.ship_to_nbr, 1, 6)+'-', InnerInvoiceHeader.sold_to_cust_seq) AS ReturnMemberID
, ReturnHeader.invoice_nbr AS ReturnInvoiceNum
, qty_received
FROM AXS.PUB.return_hdr ReturnHeader
INNER JOIN AXS.PUB.ivc_header InnerInvoiceHeader ON ReturnHeader.invoice_nbr = InnerInvoiceHeader.invoice_nbr
INNER JOIN AXS.PUB.return_line ReturnLine ON ReturnHeader.claim_nbr = ReturnLine.claim_nbr
WHERE ReturnInvoiceNum = '0001010914'
GROUP BY ReturnMemberID
, ReturnInvoiceNum
, qty_received) Returns ON CONCAT(SUBSTRING(OuterInvoiceHeader.sold_to_cust_nbr, 1, 6)+'-', OuterInvoiceHeader.sold_to_cust_seq) = Returns.ReturnMemberID
--on OuterInvoiceHeader.invoice_nbr = Returns.ReturnInvoiceNum
WHERE OuterInvoiceHeader.sold_to_cust_nbr = '000837'
AND OuterInvoiceHeader.invoice_date BETWEEN '06/01/2016' AND '06/30/2016'
AND OuterInvoiceHeader.invoice_status = '5804'
AND OuterInvoiceHeader.invoice_type = '5601'
GROUP BY CONCAT(SUBSTRING(OuterInvoiceHeader.sold_to_cust_nbr, 1, 6)+'-', OuterInvoiceHeader.sold_to_cust_seq);
Basically you need to keep in mind the order which SQL statements are executed:
FROM clause
WHERE clause
GROUP BY clause
HAVING clause
SELECT clause
ORDER BY clause
That's a computed column alias and thus the error. You should consider using the entire expression rather like
on concat(substring(OuterInvoiceHeader.sold_to_cust_nbr, 1, 6) + '-', OuterInvoiceHeader.sold_to_cust_seq) = Returns.ReturnMemberID
Instead of on OuterInvoiceHeader.MemberID = Returns.ReturnMemberID. As well, change any other place where you are using the same alias. You can and should use that alias only in a outer query and not in the same query.

inner join with multiple records

i have 2 tables TblMemberDetails,TblMemberDetailsSub am using following sql queries to fetch records
QUERY 1
SELECT (TblMemberDetails.MemFname +' '+TblMemberDetails.MemMname +' '+
TblMemberDetails.MemLname)As Name,
TblStateMaster.StateName,
TblDistMaster.DistName,
TblTaluqaMaster.TaluqaName
FROM TblMemberDetails INNER JOIN TblStateMaster
ON TblMemberDetails.StateId = TblStateMaster.StateId
INNER JOIN TblDistMaster ON TblMemberDetails.DistId = TblDistMaster.DistId
INNER JOIN TblTaluqaMaster ON TblMemberDetails.TaluqaId = TblTaluqaMaster.TaluqaId
INNER JOIN TblMemberDetailsSub ON TblMemberDetails.MemId = TblMemberDetailsSub.MemId
WHERE (TblMemberDetailsSub.MemMode = 'Provider')
AND (TblMemberDetailsSub.CycleStatus = 'Uncompleted')
GROUP BY TblMemberDetailsSub.MemId, TblMemberDetails.MemId,
TblMemberDetails.MemFname, TblMemberDetails.MemMname,
TblMemberDetails.MemLname, TblStateMaster.StateName,
TblDistMaster.DistName, TblTaluqaMaster.TaluqaName
order by TblMemberDetailsSub.MemId Asc
QUERY 2
SELECT TblMemberDetailsSub.MemId, ISNULL(sum(TblMemberDetailsSub.Amount),0) AS TotalAmount,
TblMemberDetailsSub.PayRound, TblMemberDetailsSub.PlanName
FROM TblMemberDetailsSub
WHERE (TblMemberDetailsSub.MemMode = 'Provider')
AND (TblMemberDetailsSub.CycleStatus = 'Uncompleted')
GROUP BY TblMemberDetailsSub.MemId, TblMemberDetailsSub.PayRound,
TblMemberDetailsSub.PlanName, TblMemberDetailsSub.Amount
ORDER BY TblMemberDetailsSub.MemId Asc
I just want both table result in single set (i user union but it is not working)
how can i merge both queries for single result
Group by in first query is not significant if you have only one row for each memberId in
TblStateMaster ,TblDistMaster ,TblTaluqaMaster also you are not selecting any value from TblMemberDetailsSub in first query . One way to merge the two queries is as follows:
SELECT (TblMemberDetails.MemFname +
' '+
TblMemberDetails.MemMname +
' '+
TblMemberDetails.MemLname)As Name,
TblStateMaster.StateName,
TblDistMaster.DistName,
TblTaluqaMaster.TaluqaName,
T.MemId,
T.TotalAmount,
T.PayRound,
T.PlanName
FROM
TblMemberDetails
INNER JOIN TblStateMaster ON TblMemberDetails.StateId = TblStateMaster.StateId
INNER JOIN TblDistMaster ON TblMemberDetails.DistId = TblDistMaster.DistId
INNER JOIN TblTaluqaMaster ON TblMemberDetails.TaluqaId = TblTaluqaMaster.TaluqaId
Inner join (
select TblMemberDetailsSub.MemId,
ISNULL(sum(TblMemberDetailsSub.Amount),0)As TotalAmount,
TblMemberDetailsSub.PayRound,
TblMemberDetailsSub.PlanName
from TblMemberDetailsSub
WHERE (TblMemberDetailsSub.MemMode = 'Provider')
AND (TblMemberDetailsSub.CycleStatus = 'Uncompleted')
group by TblMemberDetailsSub.MemId,TblMemberDetailsSub.PayRound,TblMemberDetailsSub.PlanName,TblMemberDetailsSub.Amount
) T ON TblMemberDetails.MemId = T.MemId
order by T.MemId Asc

How to select a single row where multiple rows exist from a table

I have two tables th_Therapy_Note and th_Approved. When a note in th_Therapy_Note gets approved, the application inserts a record to th_Approved.
A note can get rejected for several reasons after it has been approved (don't ask me why, as I did not design this app, lol). So if a note is rejected after being approved, another entry to th_Approved is inserted.
th_Approved.th_approved_isApproved is a boolean (bit) column, so depending on the status, the note entry in this table for this column in true or false
So multiple lines for the same note can exist in th_Approved with different th_Approved.th_approved_isApproved status, the last entry being the most recent one and correct status
The main purpose for the below query is to select notes that are ready to be 'finalized'. The issue with the below query is in the last inner join filter 'AND th_Approved.th_approved_isApproved = 1' This is selecting notes that effectively have been approved, meaning they should have an entry in th_Approved and th_Approved.th_approved_isApproved is true.
This works perfect for notes with single entries in th_Approved, but notes with multiple entries in th_Approved (as explained above) represent an issue if the last entry for that particular note is false. The query will still pick it up because there is at least one entry with th_Approved.th_approved_isApproved as true, even when last correct status is false. I need to only look at this last entry to be able to determine the correct status for a note and select it or not depending on the status.
Last part of the query (and th_Therapy_Note.th_note_id=16239) is just for my testing as this note has multiple entries, but the final will not have this.
How can I solve my issue? I have been looking at several strategies with no luck.....Hopefully I made sense :) thanks
SELECT Distinct Convert(varchar,th_Therapy_Note.th_note_id) as NOTEID, '054' as PROGCODE, Rtrim(ch.child_caseNumber) as CASEID,
Case th_TherapyType.shortname when 'ST' then 'SP' else rtrim(th_TherapyType.shortname) end as SERVTYPE, Convert(varchar,th_Therapy_Note.th_note_dateofservice,101) as DELSERVDATE,
Cast(((Select sum(th_TherapyServiceProvided.units) From th_TherapyServiceProvided where th_DirectServices.th_ds_id = th_TherapyServiceProvided.th_ds_id)/60) as varchar) as SERVHRS,
Cast(((Select sum(th_TherapyServiceProvided.units) From th_TherapyServiceProvided where th_DirectServices.th_ds_id = th_TherapyServiceProvided.th_ds_id)%60) as varchar) as SERVMIN,
'1' as METHOD, isnull(th_Users.trad_id, ' ') as SPROVNUM, th_Users.th_user_lname, '' as COVISIT
FROM th_Therapy_Note INNER JOIN
child_tbl AS ch ON th_Therapy_Note.child_id = ch.child_recordId INNER JOIN
th_DirectServices ON th_Therapy_Note.th_note_id = th_DirectServices.th_note_id INNER JOIN
LookUp_contactType ON th_Therapy_Note.contact_type_id = LookUp_contactType.recId INNER JOIN
th_Users ON th_Therapy_Note.service_coordinator = th_Users.th_user_email INNER JOIN
th_TherapyType ON th_Therapy_Note.therapy_type = th_TherapyType.id INNER JOIN
th_Approved ON th_Therapy_Note.th_note_id = th_Approved.th_note_id AND th_Approved.th_approved_isApproved = 1
WHERE (ch.child_recordId =
(SELECT MAX(child_recordId) AS Expr1
FROM child_tbl
WHERE (child_caseNumber = ch.child_caseNumber)))
and th_Therapy_Note.th_note_dateofservice > '4/22/2014' and th_Therapy_Note.th_note_id=16239
You can use a "MAX" trick (or "MIN" or similar). On a date or unique column is typical.
Here is a generic Northwind example that uses the MAX(OrderDate) (where a customer has more than one order).
The logic below falls apart if there are 2 orders with the same order-date, and those dates are the "max" date. So a unique identifier that is orderable is preferred)
Use Northwind
GO
Select cust.* , ords.*
from dbo.Customers cust
LEFT OUTER JOIN dbo.Orders ords
ON
(
ords.CustomerID = cust.CustomerID
AND ords.OrderDate =
(SELECT MAX(OrderDate)
FROM dbo.Orders innerords
WHERE innerords.CustomerID = cust.CustomerID
)
)
where cust.CustomerID = 'ALFKI'
Since you have a sequential ID on th_Approved, then I'd use that. Integer comparison on id is perfect. Date/Datetime comparison can sometimes add problems.
So I'd try this:
SELECT Distinct
Convert(varchar,th_Therapy_Note.th_note_id) as NOTEID,
'054' as PROGCODE,
Rtrim(ch.child_caseNumber) as CASEID,
Case th_TherapyType.shortname
when 'ST' then 'SP'
else rtrim(th_TherapyType.shortname)
end as SERVTYPE,
Convert(varchar,th_Therapy_Note.th_note_dateofservice,101) as DELSERVDATE,
Cast(((
Select sum(th_TherapyServiceProvided.units)
From th_TherapyServiceProvided
where th_DirectServices.th_ds_id = th_TherapyServiceProvided.th_ds_id)/60) as varchar
) as SERVHRS,
Cast(((
Select sum(th_TherapyServiceProvided.units)
From th_TherapyServiceProvided
where th_DirectServices.th_ds_id = th_TherapyServiceProvided.th_ds_id)%60) as varchar
) as SERVMIN,
'1' as METHOD,
isnull(th_Users.trad_id, ' ') as SPROVNUM,
th_Users.th_user_lname, '' as COVISIT
FROM th_Therapy_Note
INNER JOIN child_tbl AS ch ON th_Therapy_Note.child_id = ch.child_recordId
INNER JOIN th_DirectServices ON th_Therapy_Note.th_note_id = th_DirectServices.th_note_id INNER JOIN LookUp_contactType ON th_Therapy_Note.contact_type_id = LookUp_contactType.recId INNER JOIN th_Users ON th_Therapy_Note.service_coordinator = th_Users.th_user_email
INNER JOIN th_TherapyType ON th_Therapy_Note.therapy_type = th_TherapyType.id
INNER JOIN th_Approved ON th_Approved.th_approved_id=(
SELECT MAX(th_approved_id)
FROM th_Approved
WHERE th_Therapy_Note.th_note_id = th_Approved.th_note_id)
WHERE ch.child_recordId = (
SELECT MAX(child_recordId)
FROM child_tbl
WHERE child_caseNumber = ch.child_caseNumber)
AND th_Therapy_Note.th_note_dateofservice > '4/22/2014'
AND th_Approved.th_approved_isApproved = 1
AND th_Therapy_Note.th_note_id=16239
Without access to your dataset to test this with this is the best I can give you.
In essence what I am doing is filtering out the duplicates using a CTE and the TSQL command ROW NUMBER using whatever date function you have. then placing the filtered out list into your main query.
;with fixDuplicateCTE(
SELECT m.th_note_id, m.tag
FROM ( SELECT TH_NOTE_ID ROW_NUMBER OVER(partition by th_note_id ORDER BY [SOME DATE FUNCTION YOU HAVE!!!!!] desc) as tag FROM th_approved) as m
INNER JOIN th_approved AS a on m.th_note_id = a.th_note_id
WHERE m.tag = 1
)
SELECT Distinct Convert(varchar,th_Therapy_Note.th_note_id) as NOTEID, '054' as PROGCODE, Rtrim(ch.child_caseNumber) as CASEID,
Case th_TherapyType.shortname
when 'ST' then 'SP' else rtrim(th_TherapyType.shortname) end as SERVTYPE, Convert(varchar,th_Therapy_Note.th_note_dateofservice,101) as DELSERVDATE,
Cast(((Select sum(th_TherapyServiceProvided.units) From th_TherapyServiceProvided where th_DirectServices.th_ds_id = th_TherapyServiceProvided.th_ds_id)/60) as varchar) as SERVHRS,
Cast(((Select sum(th_TherapyServiceProvided.units) From th_TherapyServiceProvided where th_DirectServices.th_ds_id = th_TherapyServiceProvided.th_ds_id)%60) as varchar) as SERVMIN,
'1' as METHOD, isnull(th_Users.trad_id, ' ') as SPROVNUM, th_Users.th_user_lname, '' as COVISIT
FROM th_Therapy_Note
INNER JOIN child_tbl AS ch ON th_Therapy_Note.child_id = ch.child_recordId
INNER JOIN th_DirectServices ON th_Therapy_Note.th_note_id = th_DirectServices.th_note_id
INNER JOIN LookUp_contactType ON th_Therapy_Note.contact_type_id = LookUp_contactType.recId
INNER JOIN th_Users ON th_Therapy_Note.service_coordinator = th_Users.th_user_email
INNER JOIN th_TherapyType ON th_Therapy_Note.therapy_type = th_TherapyType.id
INNER JOIN fixDuplicateCTE ON th_Therapy_Note.th_note_id = th_Approved.th_note_id AND th_Approved.th_approved_isApproved = 1
WHERE (ch.child_recordId =
(SELECT MAX(child_recordId) AS Expr1
FROM child_tbl
WHERE (child_caseNumber = ch.child_caseNumber)))
and th_Therapy_Note.th_note_dateofservice > '4/22/2014' and th_Therapy_Note.th_note_id=16239

Combine SELECT statements. Help Needed

I have the following two T-SQL statements that I really need to combine:
SELECT Aircraft.Id AS AircraftID, AircraftManufacturers.Name, AircraftModels.ModelName,
Aircraft.ModelSuffix, Aircraft.ImageFileName, Aircraft.Year, Aircraft.SerialNo,
Locations.DescriptionForSite, Aircraft.Description, Aircraft.Description2,
Aircraft.InfoWebAddress, Aircraft.ImageDescription, Advertisers.Id AS AdvertisersID,
Advertisers.Name AS AdvertisersName, Aircraft.AircraftDataId, Aircraft.ForSale, Aircraft.ForLease,
Aircraft.TTAF, Aircraft.ReSend, Aircraft.ReSendReason, Aircraft.Registration, Aircraft.AdType,
Aircraft.HasAlternateImage, Aircraft.AlternateImageDescription,
Aircraft.Price, AircraftModels.AircraftType, Advertisers.CurrentEMagLink, Aircraft.CurrentEMagLink,
Aircraft.Email, Aircraft.IsSold, Aircraft.SoldDate, Aircraft.DateAdded, Aircraft.ExtendedDetails,
Aircraft.LastUpdateDate, Aircraft.ImageCount, Aircraft.ContactTelephone, AircraftModels.id, Advertisers.IsPremiumAdvertiser,
Aircraft.Location, Advertisers.ContactTelephone As AdvertisersTelephone, Aircraft.LastUpdateDate, Aircraft.EndDate, Aircraft.VideoLink
FROM (((Aircraft
INNER JOIN Advertisers ON Aircraft.AdvertiserId = Advertisers.Id)
INNER JOIN AircraftModels ON Aircraft.AircraftModelId = AircraftModels.Id)
INNER JOIN AircraftManufacturers ON AircraftModels.ManufacturerId = AircraftManufacturers.Id)
INNER JOIN Locations ON Aircraft.LocationId = Locations.Id
JOIN iter$simple_intlist_to_tbl(#ids) i ON AircraftModels.id = i.number
WHERE (Aircraft.IsActive=1 AND Advertisers.IsActive=1 AND (Aircraft.EndDate>=#Date OR Aircraft.EndDate Is Null) AND Locations.DescriptionForSite LIKE #Location)
OR (Advertisers.IsActive=1 AND Aircraft.IsSold=1 AND Aircraft.SoldDate>=#Date2 AND Locations.DescriptionForSite LIKE #Location)
ORDER BY Advertisers.IsPremiumAdvertiser ASC, Aircraft.DateAdded DESC, Aircraft.ListPosition DESC,
Aircraft.LastUpdateDate, AircraftManufacturers.Name, AircraftModels.ModelName, Aircraft.ModelSuffix,
Aircraft.Id DESC
and
SELECT TOP (1) dbo.Addresses.Email, dbo.Addresses.Contact, dbo.Addresses.Telephone1
FROM dbo.AdvertiserAddressLink
INNER JOIN dbo.Addresses ON dbo.AdvertiserAddressLink.AddressId = dbo.Addresses.Id
WHERE (dbo.AdvertiserAddressLink.AdvertiserId = 'AdvertisersID') <--see above
AND (dbo.Addresses.AddressType = 1 OR dbo.Addresses.AddressType = 0)
ORDER BY dbo.Addresses.AddressType DESC, dbo.Addresses.Sequence
It looks like you want to do TOP 1 in the second query based on a correlated parameter from the first?
You can use APPLY for this.
A simple example.
SELECT t.name, ca.name
FROM sys.tables t
CROSS APPLY (SELECT TOP 1 *
FROM sys.columns c
WHERE c.object_id=t.object_id
ORDER BY name) ca