【问题标题】:Query to pull second smallest id查询以提取第二小的 id
【发布时间】:2014-09-05 04:18:54
【问题描述】:
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(如果存在)

【问题讨论】:

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


    【解决方案1】:

    请尝试:

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

    【讨论】:

      【解决方案2】:

      您可以使用窗口函数:

      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
      

      【讨论】:

        猜你喜欢
        • 2021-02-16
        • 2012-05-10
        • 1970-01-01
        • 2015-10-24
        • 1970-01-01
        • 2013-03-01
        • 2021-09-29
        • 1970-01-01
        • 2019-04-26
        相关资源
        最近更新 更多