0

我有一个具有以下结构的表:

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

我已经阅读了这篇文章,但它不适用于我的案例,尽管它在这里有所帮助

关于谁来解决这个问题的任何想法?

4

3 回答 3

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)
)

小提琴

于 2013-10-29T21:35:01.390 回答
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

感谢安德鲁的澄清和 sqlfiddle。如果我浪费了任何人的时间,我很抱歉。

于 2013-10-30T15:34:18.630 回答
0

链接问题中缺少的东西是DISTINCT关键字。

另请参阅ypercube 发布的查询下方的说明。事实上,你得到了重复,因为你正在加入一个表本身。因此,行将被镜像。

您的子查询应该是:

(SELECT DISTINCT ID, MAX(SEQ) as MAXSEQ FROM TABLE GROUP BY ID) as T
于 2013-10-29T21:24:48.573 回答