【问题标题】:Query with order by按顺序查询
【发布时间】:2016-08-11 08:00:59
【问题描述】:

表:学生

  ID    Name    Marks
    1   Ashley   81
    2   Samantha 75
    4   Julia    76
    3   Belvet   84

返回marks大于75的名字的查询,输出将按每个名字的后三个字符排序,如果平局,则按ID升序排序。

我的查询:-

  Select Name 
    From Students 
   Where Marks > 75
Order By (Select Substring(Name,1,2))

到目前为止,我尝试过这个,我试图以某种方式找出order by,但这是错误的。我怎么能做到呢?

【问题讨论】:

  • 从 order by 中删除选择。仅子字符串就可以解决问题。
  • 为什么在order by中又选择了? (包括如果你真的想这样做,你会错过这张桌子)
  • 这个作业问题应该已经回答了吗?

标签: sql sql-server database


【解决方案1】:
SELECT Name
FROM Students 
WHERE Marks > 75
ORDER BY RIGHT(Name, 3),
         ID

你也可以使用:

ORDER BY SUBSTRING(Name, LEN(Name)-2, 3)

作为替代。

【讨论】:

  • 我只是来回试了一下,SUBSTRING 看起来很宽容,如果Name 只有一个字符,它甚至可以正常工作。当然RIGHT 看起来更好。
【解决方案2】:

ORDER BY 子句中不需要 SELECT。要按 last 三个字符而不是 first 排序,请使用:

SELECT Name
FROM Students 
WHERE Marks > 75
ORDER BY RIGHT(Name, 3), ID

要通过ID 订购领带,只需添加ID 作为第二个ORDER 参数。

【讨论】:

  • substring(Name, LEN (Name) - 3, 3 ) 是否给出名称的最后三个字符?
  • no,substring(Name, LEN (Name) - 3, 3 ) 没有给出最后三个字符...
  • @Zahid 对不起,你是对的,SQL 字符串显然是 1-indexed,所以它是 LEN()-2
  • SUBSTRING('Bo', 0, 3) 会发生什么?
  • @TimBiegeleisen 正如您所看到的,当您将此行放入 SQL 工具时,它会返回 'Bo'
【解决方案3】:
SELECT Name 
FROM Students 
WHERE Marks > 75
ORDER BY substring(Name, LEN(Name)-2, 3), ID

【讨论】:

    【解决方案4】:

    以下是您需要的部分。按它订购,然后是 id。

    select substring('THENAME', LENGTH('THENAME')-2, 3)
    

    完整代码:

    Select Name from Students 
    where Marks > 75
    order by (Substring(Name,LENGTH(Name)-2,3)), Id
    

    【讨论】:

      【解决方案5】:

      在sql中制作这个函数:

      Alter function dbo.getlastthreechar (@s varchar(256)) returns varchar(3)
         with schemabinding<
      begin
         if @s is null
            return null
         declare @s2 varchar(256)
         set @s2 = ''
         set @s2 = RIGHT(@s,3)
         if len(@s2) = 0
            return null
         return @s2
         end
      

      然后你会这样查询:

      Select Name from Students where Marks > 75 order by dbo.getlastthreechar(Name )
      

      【讨论】:

      • RIGHT(name,3) 给出字符串的最后三个字符
      • 欢迎来到 Stack Overflow!花点时间阅读帮助中心的editing help。 Stack Overflow 上的格式与其他网站不同。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-11-24
      • 2021-04-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-29
      相关资源
      最近更新 更多