SQL - 从一组记录中选择最高值

时间:2015-01-26 11:21:22

标签: sql sql-server sql-server-2008 select derby

使用DERBY DB我有类似下表的内容

table = transfers
xid = autoincrement (factor of 10)
PK (xid, phase)

xid     phase      information
------------------------------
10      1          queued
10      2          in progress
10      3          complete
20      1          queued
20      2          in progress
30      1          queued
30      2          in progress
30      11         failed

我想要的是一个只提取每个xid的最高阶段号的查询。每个xid一行。

本质上,只会撤回以下行

xid     phase      information
------------------------------
10      3          complete
20      2          in progress
30      11         failed

SELECT xid,阶段,信息FROM转移WHERE ....(帮帮我)

感谢任何帮助。

3 个答案:

答案 0 :(得分:3)

使用Window Function

SELECT xid,
       phase,
       information
FROM   (SELECT *,Row_number()OVER(partition BY xid ORDER BY phase) Rn               
        FROM   yourtable)
WHERE  rn = 1 

或使用max聚合来查找每个phase中的最大xid,然后将结果重新加入表格。

SELECT a.xid,
       a.phase,
       a.information
FROM   yourtable a
       JOIN (SELECT Max(phase) phase,
                    xid
             FROM   yourtable
             GROUP  BY xid) B
         ON a.phase = b.phase
            AND a.xid = b.xid 

答案 1 :(得分:2)

使用MAX和GROUP BY

SELECT xid, MAX(phase), information
FROM transfers
GROUP BY xid, information

答案 2 :(得分:1)

select xid, max(phase), information from transfers group by xid, information