SQL Server 2008 - 在没有PIVOT的列中显示行项

时间:2017-04-20 06:36:10

标签: sql-server sql-server-2008

我有三个表存储:TENANT,ROOMMATE和PERSON记录。

架构如下:

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

TENANT表包含TENANT记录。 ROOM表包含占用者记录。 PERSON表包含所有类型的人(TENANT,ROOMMATE,VENDOR等)。

ROOM表中的HMYTENANT是TENANT表(HMYPERSON)的外键

ROOM表中的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个室友就足够了。

感谢您的帮助。

1 个答案:

答案 0 :(得分: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