0

I have table T1

ID  X  Y  ProtocolID
 1  4  2         100
 2  9  0         101
 3  5  1         104

and table T2

ID  Entry  Category  ProtocolID
 1  "XYZ"       700         100
 2  "ABC"       701         100
 3  "UZT"       702         100
 4  "TRS"       704         100
 5  "YBS"       700         101
 6  "VTX"       701         101
 7  "SAJ"       702         101
 8  "POL"       710         101
 9  "UIT"       700         104
10  "UCN"       701         104
11  "POI"       702         104   

I need to join the tables on ProtocolID and put Entries with Category value 700, 701, 702 into a single row. The resulting table should look like

T1.ID  X  Y  Entry700  Entry701  Entry702
    1  4  2     "XYZ"     "ABC"     "UZT"
    2  9  0     "YBS"     "VTX"     "SAJ"
    3  5  1     "UIT"     "UCN"     "POI"
Phil
  • 1

3 Answers3

1

A basic pivot query with a join should work here:

SELECT
    t1.ID,
    t1.X,
    t1.Y,
    MAX(CASE WHEN t2.Category = 700 THEN t2.Entry END) Entry700,
    MAX(CASE WHEN t2.Category = 701 THEN t2.Entry END) Entry701,
    MAX(CASE WHEN t2.Category = 702 THEN t2.Entry END) Entry702,
    MAX(CASE WHEN t2.Category = 703 THEN t2.Entry END) Entry703,
    MAX(CASE WHEN t2.Category = 704 THEN t2.Entry END) Entry704
FROM T1 t1
INNER JOIN T2 t2
    ON t1.ProtocolID = t2.ProtocolID
GROUP BY
    t1.ID,
    t1.X,
    t1.Y;
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
1

Try something like:

select t1.id, t1.x, t1.y, (select t2.entry from t2 where t1.id=t2.id and 
t2.category=700) as entry_700  from t1
JanFi86
  • 449
  • 10
  • 29
0

This should work

SELECT *
FROM ( SELECT t1.id1,
           x,
           y,
           entry1,
           cat
    FROM t1,
         t2
    WHERE t1.protoid = t2.protoid )
        PIVOT ( MAX ( entry1 ) AS entry1
            FOR cat
            IN ( 700,701 )
        );
user14063792468
  • 839
  • 12
  • 28
Mansi Raval
  • 371
  • 6
  • 14