查询以获取第二个最小的ID

时间:2014-07-15 05:14:13

标签: sql sql-server group-by aggregate-functions min

CUSTOMER(ID,CASE_ID,NAME,STATE)

          1,100,Alex,NY
          2,100,Alex,VA
          3,100,Alex,CT
          4,100,Tom,PA
          5,102,Peter,MO
          6,103,Dave,TN
          .
          .
          .

如何编写查询以为每个case_id组提取第二个最小(最小)id(如果存在)

2 个答案:

答案 0 :(得分:3)

请尝试:

SELECT
    ID,
    CASE_ID
FROM
(
    SELECT 
        *,
        ROW_NUMBER() OVER(PARTITION BY CASE_ID ORDER BY ID) Rn
    FROM CUSTOMER
)x
WHERE Rn=2

答案 1 :(得分:1)

您可以使用窗口函数:

with cte as (
    select ID, CASE_ID, ROW_NUMBER() over (partition by CASE_ID order by ID) rn
    from CUSTOMER
)
select ID, CASE_ID
from cte
where rn = 2

或者您可以使用exists子句删除第一行(即,如果行的值较低,则获取最小值):

select MIN(ID) ID, CASE_ID
from CUSTOMER c
where exists (select 1 from CUSTOMER c2 where c2.ID < c.ID and c2.CASE_ID = c.CASE_ID)
group by CASE_ID

或者,写另一种方式:

select MIN(ID) ID, CASE_ID
from CUSTOMER c
where c.ID > (select MIN(ID) from CUSTOMER c2 where c2.CASE_ID = c.CASE_ID)
group by CASE_ID