2017-04-20 61 views
0

我有三個表存儲:TENANT,ROOMMATE和PERSON記錄。SQL Server 2008 - 顯示沒有PIVOT的列中的行項目

架構是如下:

Table: Tenant 
HMYPERSON SCODE sFirstName sLastName 
     1 t0011 fName  lName 

Table: room 
HMYPERSON HMYTENANT sRelationShip 
    9458   1 Roommate 
    1024   1 Other 
    1025   1 Roommate 
    1026   1 Guarantor 

Table: Person 
HMY  UCODE ULASTNAME sFIRSTNAME  iPersonType 
9458 r0011 roommate1 roommate1Fname 93 
1024 r0012 roommate2 roommate2Fname 93 
1025 r0013 roommate3 roommate3Fname 93 
1026 r0014 roommate4 roommate4Fname 90 

租戶表包含承租人記錄。 ROOM表包含佔有者記錄。 和Person表包含所有類型的人在裏面(租戶,室友,供貨商等)

HMYTENANT在室的桌子是租戶表(HMYPERSON)的外鍵

HMYPERSON在表空間是一個外鍵PERSON表格(HMY)

PERSON表格中的IPERSONTYPE指定它是什麼類型的人員記錄。 (93是室友,90是擔保人)

我想在一行中顯示所有租戶和他們的室友名稱。 所有的室友應顯示在同一行和不同的列中。 (每個室友一列)

我寫了一個查詢,給了我室友的列表,但在行中。

這是我採寫:

Select t.scode, t.sLastname + ' ' + t.sFIRSTNAME TenantName, p.ULASTNAME + ' ' + p.sFIRSTNAME RoommateName 
from tenant t 
join room r on r.hmytenant = t.hmyperson 
left join person p on p.hmy = r.hmyperson and (r.sRelationship <> 'Guarantor' or p.IPERSONTYPE<>90) 
where t.hmyperson=1 

這給了我輸出象下面這樣:

scode Tenantname  RoommateName 
t0011 lName fName  roommate1 roommate1Fname 
t0011 lName fName  roommate2 roommate2Fname 
t0011 lName fName  roommate3 roommate3Fname 

但我想它想:

scode  Tenantname  Roommate1  Roommate2  Roommate3 

多達5個室友是足夠。

感謝您的幫助。

+0

參見:http://modern-sql.com/use-case/pivot –

回答

0

你可以試試嗎?

WITH A AS (SELECT HMYPERSON, HMYTENANT, SRELATIONSHIP, P.ULASTNAME, p.SFIRSTNAME, ROW_NUMBER() OVER (PARTITION BY HMYTENANT ORDER BY HMYPERSON) AS RN 
      FROM ROOM R 
      INNER JOIN PERSON P ON P.HMY = R.HMYPERSON 
           AND (R.SRELATIONSHIP <> 'Guarantor' OR P.IPERSONTYPE<>90)   
      ) 
SELECT T.SCODE, T.SLASTNAME + ' ' + T.SFIRSTNAME TENANTNAME 
     , A1.ULASTNAME + ' ' + A1.SFIRSTNAME ROOMMATENAME_1 
     , A2.ULASTNAME + ' ' + A2.SFIRSTNAME ROOMMATENAME_2 
     , A3.ULASTNAME + ' ' + A3.SFIRSTNAME ROOMMATENAME_3 
     , A4.ULASTNAME + ' ' + A4.SFIRSTNAME ROOMMATENAME_4 
     , A5.ULASTNAME + ' ' + A5.SFIRSTNAME ROOMMATENAME_5 
FROM TENANT T 
LEFT JOIN A A1 ON A1.HMYTENANT = T.HMYPERSON AND A1.RN=1 
LEFT JOIN A A2 ON A2.HMYTENANT = T.HMYPERSON AND A2.RN=2 
LEFT JOIN A A3 ON A3.HMYTENANT = T.HMYPERSON AND A3.RN=3 
LEFT JOIN A A4 ON A4.HMYTENANT = T.HMYPERSON AND A4.RN=4 
LEFT JOIN A A5 ON A5.HMYTENANT = T.HMYPERSON AND A5.RN=5 
WHERE T.HMYPERSON=1 

輸出:

SCODE TENANTNAME ROOMMATENAME_1   ROOMMATENAME_2   ROOMMATENAME_3   ROOMMATENAME_4   ROOMMATENAME_5 
----- ----------- ------------------------ ------------------------ ------------------------ ------------------------ ------------------------ 
t0011 lName fName roommate2 roommate2Fname roommate3 roommate3Fname roommate1 roommate1Fname NULL    NULL