我有桌子T1
ID X Y ProtocolID
1 4 2 100
2 9 0 101
3 5 1 104
和表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
我需要在ProtocolID
上联接表,并将Category
值700
,701
,702
的条目放入一行。生成的表应该看起来像
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"
答案 0 :(得分:1)
具有联接的基本数据透视查询应该在这里工作:
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;
答案 1 :(得分:1)
尝试类似的东西:
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
答案 2 :(得分:0)
这应该有效
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 )
);