T-SQL returns the previous or next value

Source: Internet
Author: User

The "previous" concept implies a logical ordering, but we know that the rows in the table are in a non-bony order, and we need to provide a concept that is equivalent to the "previous" and can be expressed in T-SQL expressions. An example of this logical equivalence is the "maximum value less than the current value". In T-SQL, you can use a related subquery such as the following to express the phrase:

SELECT Orderid,orderdate,empid,custid,

(SELECT MAX (O2.orderid) from order as, WHERE 02.orderid<01.orderid) As Prevorderid

From order as 01;

Note that because there are no orders before the first one, the subquery returns a null value for the first order.


Similarly, the "next" concept can be expressed as "a minimum value greater than the current value." Below is a T-SQL query that returns the next order ID for each order.

SELECT Orderid,ordate,empid,custid

(SELECT MIN (OrderID) from order as, WHERE 02.orderid>01.orderid) As Nextorderid

From Orders as 01;

Note that because there will be no orders after the last one, the subquery returns null for the last order.



This article is from the "Growth Cornerstone" blog, be sure to keep this source http://jeffxi.blog.51cto.com/8540759/1641101

T-SQL returns the previous or next value

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.