1

I have a SQL Server table with the following fields and sample data:

ID         Name   Address   Age
23052-PF   Peter  Timbuktu  25
23052-D1   Jane   Paris     22
23052-D2   David  London    24
23050-PF   Sam    Beijing   22
23051-PF   Nancy  NYC       26
23051-D1   Carson Cali      22
23056-PF   Grace  LA        28
23056-D1   Smith  Boston    23
23056-D2   Mark   Adelaide  26
23056-D3   Hose   Mexico    25
23056-D4   Mandy  Victoria  24

Each ID with -PF is unique in the table.

Each ID with the -Dx is related to the same ID with the -PF.

Each ID with -PF may have 0 or more IDs with -Dx.

The maximum number of -Dx rows for a given -PF is 9.

i.e. an ID 11111-PF can have 11111-D1, 11111-D2, 11111-D3 up to 11111-D9.

Output expected for above sample data:

ID        ID (without suffix)  PF_Name  PF_Address  PF_Age  D_Name   D_Address   D_Age
23052-PF  23052                Peter    Timbuktu    25      Jane     Paris       22
23052-PF  23052                Peter    Timbuktu    25      David    London      24
23050-PF  23050                Sam      Beijing     22      NULL     NULL        NULL
23051-PF  23051                Nancy    NYC         26      Carson   Cali        22
23056-PF  23056                Grace    LA          28      Smith    Boston      23
23056-PF  23056                Grace    LA          28      Mark     Adelaide    26
23056-PF  23056                Grace    LA          28      Hose     Mexico      25
23056-PF  23056                Grace    LA          28      Mandy    Victoria    24

I need to be able to join the -PF and -Dx as above.

If a -PF has 0 Dx rows, then D_Name, D_Address and D_Age columns in the output should return NULL.

If a -PF has one or more Dx rows, then PF_Name, PF_Address and PF_Age should repeat for each row in the output and D_Name, D_Address and D_Age should contain the values from each related Dx row.

Need to use MSSQL.

Query should not use views or create additional tables.

Thanks for all your help!

4

2 回答 2

1
select 
    pf.ID,
    pf.IDNum,
    pf.Name as PF_Name,
    pf.Address as PF_Address,
    pf.Age as PF_Age,
    dx.Name as D_Name,
    dx.Address as D_Address,
    dx.Age as D_Age

from

(
select
    ID, left(ID, 5) as IDNum, Name, Address, Age

from
    mytable

where
    right(ID, 3) = '-PF'
) pf

left outer join

(
select
    ID, left(ID, 5) as IDNum, Name, Address, Age

from
    mytable

where
    right(ID, 3) != '-PF'
) dx

on pf.IDNum = dx.IDNum

SqlFiddle 演示:http ://sqlfiddle.com/#!6/dfdbb/1

于 2013-05-13T21:44:29.537 回答
0
SELECT t1.ID, LEFT(t1.ID,5) "ID (without Suffix)",
    t1.Name "PF_Name", t1.Address "PF_Address", t1.Age "PF_Age",
    t2.Name "D_Name", t2.Address "D_Address", t2.Age "D_Age"
FROM PFTable t1
LEFT JOIN PFTable t2 on LEFT(t1.ID,5) = LEFT(t2.ID,5)
WHERE RIGHT(t1.ID,2) = 'PF'
于 2013-05-13T21:53:30.133 回答