zoukankan      html  css  js  c++  java
  • 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

     

  • 相关阅读:
    mybatis 控制台打印sql脚本
    删除git库中untracked files(未监控)的文件
    亚马逊云实例被攻击 一个月账单三百多美刀
    ubuntu下搜索文件
    django 富文本展示 以及 post提交出错
    亚马逊EC2弹性IP收费
    redis 相关命令
    使用XSHELL连接EC2虚拟机实例
    springMVC下集成active MQ发送邮件
    ubuntu下安装JDK并搭建activeMQ
  • 原文地址:https://www.cnblogs.com/zhaochengshen/p/5618488.html
Copyright © 2011-2022 走看看