hi Walter
Please click arrow to the left for ... drop create tables
with sample data
drop create tables with sample data
drop table #tbl_quote
create table #tbl_quote
(
QuoteID int PRIMARY KEY,
CaseID int FOREIGN KEY REFERENCES #tbl_case(caseid),
QuoteNumber int ,
Value int ,
QuoteDate date
)
insert into #tbl_quote select 1,11,1,100,'2020-02-09'
insert into #tbl_quote select 2,11,2,200,'2020-02-10'
insert into #tbl_quote select 3,11,3,300,'2020-02-11'
insert into #tbl_quote select 4,11,4,400,'2020-02-11'
insert into #tbl_quote select 5,11,5,500,'2020-02-11'
insert into #tbl_quote select 6,11,6,700,'2020-02-11'
select 'tbl_quote',* from #tbl_quote
drop table #tbl_case
go
create table #tbl_case
(
caseid int PRIMARY KEY,
casenumber int ,
casedate date ,
ContactID int FOREIGN KEY REFERENCES #tbl_Contact(contactid)
)
insert into #tbl_case select 11,2,'2020-09-10',145
insert into #tbl_case select 12,3,'2020-07-10',147
select 'tbl_case',* from #tbl_case
drop table #tbl_contact
go
create table #tbl_Contact
(
contactid int PRIMARY KEY,
accountid int FOREIGN KEY REFERENCES #tbl_account(accountid),
firstname varchar(100),
lastname varchar(100),
emailaddress varchar(100),
TelePhoneNumber int
)
go
insert into #tbl_Contact select 145,1002,'ops','sam','sure@gmail.com',98888
insert into #tbl_Contact select 147,1003,'har','sap','ok@gmail.com',985666
go
select 'tbl_contact',* from #tbl_Contact
go
drop table #tbl_account
go
create table #tbl_account
(
AccountId int PRIMARY KEY,
ParentAccountId int ,
Address1 varchar(100),
Address2 varchar(100),
Address3 varchar(100),
PostCode int
)
go
insert into #tbl_account select 1002,999,'sssss','yyyy','zzzz',500023
insert into #tbl_account select 1003,999,'asass','qwsq','edrr',500024
go
select 'tbl_account',* from #tbl_account
; WITH cte
AS (SELECT Row_number()
OVER(
partition BY d.accountid
ORDER BY value DESC) AS rn
,QuoteID
,b.CaseID
,QuoteNumber
,Value
,QuoteDate
,casenumber
,casedate
,c.ContactID
,d.accountid
,lastname
,emailaddress
,TelePhoneNumber
,ParentAccountId
,Address1
,Address2
,Address3
,PostCode
FROM #tbl_quote a
JOIN #tbl_case b
ON a.caseid = b.caseid
JOIN #tbl_contact c
ON b.contactid = c.contactid
JOIN #tbl_account d
ON c.accountid = d.accountid
)
SELECT 'SQL Output',
AccountId AS [account name],
lastname AS [contact last name],
casenumber AS [case number],
quotenumber AS [quote number],
quotedate AS [quote date],
value AS [quote value]
FROM CTE
WHERE postcode = 500023 -- EC1 Area
AND rn = 3