我有一个具有以下结构的表:
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
我已经阅读过这篇文章,但它不适用于我的案例,尽管它有助于here
有关谁解决这个问题的想法?
答案 0 :(得分:1)
SELECT
id, amount, type
FROM TABLE1
natural join (SELECT ID, MAX(SEQ) as SEQ FROM TABLE1 GROUP BY ID)
pivot (
max(VALUE) for key in ('Amount' as amount, 'Type' as type)
)
答案 1 :(得分:0)
the linked question中遗漏的内容是DISTINCT
关键字。
另请参阅下面的解释the query posted by ypercube。事实上,你正在获得重复,因为你自己加入了一个表。因此,行将被镜像。
你的子查询应该是:
(SELECT DISTINCT ID, MAX(SEQ) as MAXSEQ FROM TABLE GROUP BY ID) as T
答案 2 :(得分:0)
我意识到还有另一个专栏,我没有提出影响结果的问题(以避免发出实际数据)。唯一约束是(ID,Key,Seq,Time)而不是(ID,Key,Seq)。正如@Andrew提到的那样,查询返回了正确的结果。
再次进行查询
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
感谢Andrew的澄清和sqlfiddle。如果我浪费了任何人的时间,我道歉。