【问题标题】:How to compare values of the same column and return true/false?如何比较同一列的值并返回真/假?
【发布时间】:2020-10-26 11:58:21
【问题描述】:

我正在尝试构建一个查询,该查询将比较特定列的最后两个值,如果数字上升则返回 true,如果下降则返回 false。

如何使用 MS SQL 实现这一点?

数据是这样的

门票:

71

72

73

74

75

假设我想获取最新的两个并比较它们,然后返回一个布尔值。可以实现吗?

【问题讨论】:

  • SQL 表代表 无序 集合。没有“最新”之类的东西,除非您有一列指定该信息。

标签: sql sql-server boolean


【解决方案1】:

一种方法是单独获取每个并进行比较:

select (case when last_but_one.ticket < last_one.ticket then 'less than'
             when last_but_one.ticket = last_one.ticket then 'equal'
             when last_but_one.ticket > last_one.ticket then 'greater than'
        end)
from (select t.*
      from t
      order by ord desc
      offset 0 row fetch first 1 row only
     ) last_one cross join
     (select t.*
      from t
      order by ord desc
      offset 1 row fetch first 1 row only
     ) last_but_one;

Here 是一个 dbfiddle。

【讨论】:

  • 所以我有一列指定日期时间,称为日期时间。但是在尝试运行您的查询时,我遇到了错误。 Msg 156, Level 15, State 1, Line 8 Incorrect syntax near the keyword 'fetch'. Msg 153, Level 15, State 2, Line 8 Invalid usage of the option first in the FETCH statement. Msg 156, Level 15, State 1, Line 12 Incorrect syntax near the keyword 'order'. Msg 153, Level 15, State 2, Line 13 Invalid usage of the option first in the FETCH statement.
  • @MightySwami 。 . .我修复了错误并添加了一个小提琴。
  • @MightySwami,如果您想要一个可行的解决方案,请将带有示例数据的 CREATE TABLEINSERT 语句添加到您的问题中。否则,答案只能猜测。
  • 谢谢戈登!通过进行一些调整,我能够根据自己的使用情况对其进行自定义。
猜你喜欢
  • 2017-04-08
  • 1970-01-01
  • 2013-06-14
  • 2014-12-15
  • 2014-10-05
  • 1970-01-01
  • 1970-01-01
  • 2013-06-16
  • 1970-01-01
相关资源
最近更新 更多