• SQL Server with ties 语句


    With ties 语句是与top、order by 语句联合使用的语句;我们在实际查询过程中会遇到这样的情况,比如查询考试为前三名的学生信息,发现有并列第三的情况,如果我们只是top 3 发现并列第三的学生信息有的没有显示出来,基于这种情况我们就需要结合with ties 语句进行查询。With ties语句作用查询出,根据top筛选出的最后一条记录中和order by [字段] 相同值的其他记录。

    示例:

    1、  首先我们创建一个简单的学生成绩表;然后添加10条测试数据;

      create table StudentScore(

      id int not null primary key identity(1,1),

      studentName varchar(50),

      Score int

      )

     

     insert into StudentScore(studentName,Score) VALUES

        ('Name1',99),

        ('Name2',98),

        ('Name3',97),

        ('Name4',97),

        ('Name5',96),

        ('Name6',94),

        ('Name7',93),

        ('Name8',92),

        ('Name9',91),

        ('Name10',89)

     

     select * from StudentScore

     

    --现在我们找出考试成绩最好的前三名

    select top 3* from StudentScore order by Score desc

     

     --现在问题来了,我们发现得分为97的有两个学生,其实他们是并列第3的,但是只显示了一个得分为97的学生信息;现在就要用到with ties 语句了  

    select top 3 with ties * from StudentScore order by Score desc

     

     -- 我们这里指定了top 3 却输出了4行记录;首先查询结果返回的是基于order by score的top 3 行,然后返回top3中最后一行与score值相同的其他行;

     -- Tips:With ties 语句只能与top、order by 同时使用

    -- 不和top 、order by 结合使用

    select with ties * from studentScore

     

     -- 不和order by 结合使用

    select top 3 with ties * from StudentScore

     

    -- 不和top 结合使用

    select with ties * from studentScore order by score

     

  • 相关阅读:
    C语言编程练习51:今年暑假不AC
    C语言编程练习50:素数环
    C语言编程练习49:N皇后问题
    C语言编程练习48:士兵队列训练问题
    C语言编程练习47:看病要排队
    C语言编程练习46:度度熊学队列
    C语言编程练习44:产生冠军
    文言句式
    计算机网络
    计算机组成原理
  • 原文地址:https://www.cnblogs.com/zhaochengshen/p/5618488.html
Copyright © 2020-2023  润新知