选择组中的第一行

时间:2017-03-06 12:57:10

标签: sql oracle


我拿到了这张桌子:
enter image description here
我收到了这个请求:

SELECT FirstId,SecondId
FROM Table  
GROUP BY FirstId,SecondId
ORDER BY CASE 
    WHEN SecondId= 18 
        THEN 1
        ELSE 2 
END

所以我得到了这个结果:
enter image description here
但我想只获得由FirstId分组的行,并按照第一个请求进行排序,如下所示:
 enter image description here

1 个答案:

答案 0 :(得分:1)

这是你想要的吗?

SELECT FirstId,
       (CASE WHEN SUM(CASE WHEN SecondId = 18 THEN 1 ELSE 0 END) > 0
             THEN 18 ELSE MAX(SecondId)
        END) as SecondId
FROM Table  
GROUP BY FirstId
ORDER BY FirstId;