我有一个具有以下结构的表:
ID KEY VALUE SEQ
1 Amount 5 2
1 Amount 4 1
1 Type T1 2
1 Type T1 1
2 Amount 10 2
2 Amount 5 1
2 Type T2 2
2 Type T2 1
我想创建一个查询来得到这个:
ID Amount Type
1 5 T1
2 10 T2
如您所见,(ID, Key) 可能有多种组合,但 (ID, Key, Seq) 是唯一的。
SELECT T.ID,
T1.VALUE as Amount,
T2.VALUE as Type
FROM
(SELECT ID, MAX(SEQ) as MAXSEQ FROM TABLE GROUP BY ID) as T
JOIN
TABLE as T1
ON T1.ID = T.ID
AND T1.KEY = 'Amount'
AND T1.SEQ = MAXSEQ
JOIN
TABLE as T2
ON T2.ID = T.ID
AND T2.KEY = 'Type'
AND T2.SEQ = MAXSEQ
但我得到了我没想到的结果
ID Amount Type
1 5 T1
1 4 T1
1 10 T1
1 5 T1
2 10 T2
2 5 T2
2 4 T2
2 5 T2
我已经阅读了这篇文章,但它不适用于我的案例,尽管它在这里有所帮助
关于谁来解决这个问题的任何想法?