Another option (also using ROW_NUMBER
, but arguably a bit cleaner):
with
-- this is just to generate the test data. You'd use your actual table instead.
Data(ID, Address, SalePrice, PricePerArea, AppraisalReportID) as (
select 1, '2560 W Central Ave', 115000, 98.46, 1
union
select 2, '543 N Logan', 110000, 94.18, 1
union
select 3, '321 Wall Street', 115000, 98.46, 1
union
select 4, '5441 N East Road', 125000, 94.65, 2
union
select 5, '2365 N Califnia Ave', 118000, 92.35, 2
union
select 6, '1526 W 18th Place', 12000, 91.54, 2
)
-- you don't need this CTE if you have another table somewhere that stores Appraisal Report IDs
,AppraisalReports([id]) as (select distinct AppraisalReportID from Data)
-- this just gives you your table data + ROW_NUMBER values
,DataWithRowNum(id, Address, SalesPrice, PricePerArea, AppraisalReportID, rn) as (
select *, ROW_NUMBER() over (partition by AppraisalReportID order by ID)
from Data
)
-- the actual query, using ROW_NUMBER values for 3 separate joins
select
AppraisalReports.id AppraisalReportID
-- Record 1
,Record1.Address Address1
,Record1.SalesPrice SalesPrice1
,Record1.PricePerArea PricePerArea1
-- Record 2
,Record2.Address Address2
,Record2.SalesPrice SalesPrice2
,Record2.PricePerArea PricePerArea2
-- Record 3
,Record3.Address Address3
,Record3.SalesPrice SalesPrice3
,Record3.PricePerArea PricePerArea3
from AppraisalReports
inner join DataWithRowNum Record1 on
Record1.AppraisalReportID = AppraisalReports.id
and Record1.rn = 1
inner join DataWithRowNum Record2 on
Record2.AppraisalReportID = AppraisalReports.id
and Record2.rn = 2
inner join DataWithRowNum Record3 on
Record3.AppraisalReportID = AppraisalReports.id
and Record3.rn = 3
gives you this result:
+-------------------+--------------------+-------------+---------------+---------------------+-------------+---------------+-------------------+-------------+---------------+
| AppraisalReportID | Address1 | SalesPrice1 | PricePerArea1 | Address2 | SalesPrice2 | PricePerArea2 | Address3 | SalesPrice3 | PricePerArea3 |
+-------------------+--------------------+-------------+---------------+---------------------+-------------+---------------+-------------------+-------------+---------------+
| 1 | 2560 W Central Ave | 115000 | 98.46 | 543 N Logan | 110000 | 94.18 | 321 Wall Street | 115000 | 98.46 |
| 2 | 5441 N East Road | 125000 | 94.65 | 2365 N Califnia Ave | 118000 | 92.35 | 1526 W 18th Place | 12000 | 91.54 |
+-------------------+--------------------+-------------+---------------+---------------------+-------------+---------------+-------------------+-------------+---------------+