zoukankan      html  css  js  c++  java
  • 面试遇到的问题 老猫

    一个表,两个字段,A、B,取出每个A类型的B由大到小排列的前两个。

    create table test_a
    (
       a varchar2(10),
       b int
    )
    truncate table test_a;

    insert into test_a values ('a',10);
    insert into test_a values ('a',1);
    insert into test_a values ('a',2);
    insert into test_a values ('a',3);
    insert into test_a values ('a',4);
    insert into test_a values ('a',5);
    insert into test_a values ('a',6);
    insert into test_a values ('b',12);
    insert into test_a values ('b',14);
    insert into test_a values ('b',1);
    insert into test_a values ('b',6);
    insert into test_a values ('c',2);
    insert into test_a values ('c',4);
    insert into test_a values ('c',4);
    insert into test_a values ('c',5);
    insert into test_a values ('c',3);
    insert into test_a values ('c',15);
    insert into test_a values ('d',1);
    insert into test_a values ('d',0);
    insert into test_a values ('d',8);
    insert into test_a values ('d',6);
    insert into test_a values ('d',4);
    insert into test_a values ('d',3);
    commit;

    --杨毅给出的答案如下 (没有使用分析函数)

    --测试结果显示没显示去重,不过与题干无关。

    SELECT *
      FROM TEST_A A
     WHERE A.B IN
           ((SELECT MAX(B.B) FROM test_a B WHERE A.A = B.A) UNION
            (SELECT MAX(C.B)
               FROM TEST_A C
              WHERE A.A = C.A
                AND C.B NOT IN
                    (SELECT MAX(D.B) FROM TEST_A D WHERE A.A = D.A)))
     ORDER BY A.A ASC, A.B DESC;

    --本人答案 (使用分析函数)


    SELECT * FROM (
     SELECT a, b, ROW_NUMBER()
      OVER (
        PARTITION BY a ORDER BY b DESC
      ) Top2 FROM test_a
    )
    WHERE Top2 <= 2 ;

  • 相关阅读:
    C#创建Windows Service(Windows 服务)基础教程
    c#写windows服务
    怎么样快速学习AngularJS?
    Web API 安全问题
    ASP.NET Web API身份验证和授权
    通过HttpClient来调用Web Api接口~续~实体参数的传递
    在WebApi中实现Cors访问
    SQL Server 动态生成数据库所有表Insert语句
    EasyUI combobox
    Linq使用Group By 1
  • 原文地址:https://www.cnblogs.com/oldcat/p/2134209.html
Copyright © 2011-2022 走看看