I have about 35 tables. I want to use them in the same query. I do not know how it possible.
I have three tables:
land
lid name meter address picid
owner
ownerid name family mobile lid
Every land can have a maximum of 12 owners.
pic
picid path picinfo
The result that I need:
lid, name, meter, address, path, picinfo, owner_name_1, owner_family_1, owner_mobile_1, owner_name_2, owner_family_2, owner_mobile_2, .... owner_name_12, owner_family_12, owner_mobile_12
Best Answer
Tables
Sample data
Solution
Output
Execution plan
Solution description
The basic idea is that joining the three tables is easy. You don't even need an outer join at all if there is no land without an owner. The problem is that this produces rows, where you want columns in your output, with the columns numbered by owner. The numbering part is easy, using
ROW_NUMBER
.Turning rows into columns is known as a pivot, the expanded form of which uses
MAX
,CASE
, andGROUP BY
as shown in the above code. You just need to repeat theMAX(CASE...
sections to accommodate twelve possible owners.There are a number of good questions and answers tagged pivot on the site already that you might like to look at. One relevant to your current problem is Need help with SQL Server PIVOT.