我有这张桌子:
Profile_id Phase_id order
30087853 30021628 525
30087853 30021635 523
30087853 30021673 122
30087853 30021703 521
从上面我想得到profile_id以及这个具有最低order_num的phase_id,所以结果将如下:
Profile_id Phase_id order
30087853 30021673 122
答案 0 :(得分:2)
您没有指定DBMS,因此这是标准SQL:
select profile_id, phase_id, "order"
from (
select profile_id, phase_id, "order",
row_number() over (partition by profile_id order by "order") as rn
from the_table
) t
where rn = 1;
答案 1 :(得分:1)
如果没有子查询或自我加入,您也可以使用这个:
SELECT Profile_id, MIN("order") as "order",
MIN(Phase_id) KEEP (DENSE_RANK FIRST ORDER BY "order") AS Phase_id
FROM your_table
GROUP BY Profile_id;
答案 2 :(得分:0)
CREATE TABLE #table(Profile_id INT,Phase_id INT,_order INT) INSERT INTO #table(Profile_id,Phase_id,_order) 选择30087853,30021628,525 UNION ALL 选择30087853,30021635,523 UNION ALL 选择30087853,30021673,122 UNION ALL 选择30087853,30021703,521
SELECT * 来自#table T1 加入 ( SELECT Profile_id ProfileId,MIN(_ order)[order] 来自#table GROUP BY Profile_id )A ON T1.Profile_id = ProfileId AND T1._order = [order]