admin

如何获得下一个/上一个记录号?

sql

如何获取SQL Server中的先前记录号?

数据表:

Name   | SO No.
-----------------
Adrian | SO-00001
Adrian | SO-00002
Bianca | SO-00003
Carrie | SO-00004
Adrian | SO-00005
Bianca | SO-00006
Adrian | SO-00007

我如何获得如下结果:

Name   | SO No.   | Previous SO
-------------------------------
Adrian | SO-00005 | SO-00002

阅读 129

收藏
2021-07-01

共1个答案

admin

这将在所有主要的RDBMS(包括SQL Server和MySql)中都相同

*根据您的评论 *更新

SELECT name, 
       so_no,
       (
         SELECT MAX(so_no)
           FROM table1
          WHERE so_no < t.so_no
            AND name = t.name
       ) prev_so_no
  FROM table1 t
 WHERE so_no = 'SO-00005'

SQL Server:

*根据您的评论 *更新

SELECT name, 
       MAX(so_no) so_no, 
       CASE WHEN MAX(so_no) = MIN(so_no) 
            THEN NULL
            ELSE MIN(so_no)
       END prev_so_no
  FROM
(
  SELECT TOP 2 t1.name, t1.so_no
    FROM table1 t1 JOIN table1 t2
      ON t1.name = t2.name
   WHERE t2.so_no = 'SO-00005'
     AND t1.so_no <= t2.so_no
   ORDER BY so_no DESC
) q
   GROUP BY name

如果您使用的是 SQL Server 2012,
则还可以利用分析功能LAG

SELECT name, so_no, prev_so_no
  FROM
(
  SELECT name, so_no,
         LAG(so_no, 1, NULL) OVER (ORDER BY so_no) prev_so_no,
         ROW_NUMBER() OVER (ORDER BY so_no DESC) rnum
    FROM table1
   WHERE name = 'Adrian'
     AND so_no <= 'SO-00005'
) q
WHERE rnum = 1

或者

SELECT TOP 1 name, so_no, prev_so_no
  FROM
(
  SELECT name, so_no,
         LAG(so_no, 1, NULL) OVER (ORDER BY so_no) prev_so_no
    FROM table1
   WHERE name = 'Adrian'
     AND so_no <= 'SO-00005'
) q
 ORDER BY so_no DESC

MySQL:

SELECT name, 
       MAX(so_no) so_no, 
       CASE WHEN MAX(so_no) = MIN(so_no) 
            THEN NULL
            ELSE MIN(so_no)
       END prev_so_no
  FROM
(
  SELECT name, so_no
    FROM table1
   WHERE name = 'Adrian'
     AND so_no <= 'SO-00005'
   ORDER BY so_no DESC
   LIMIT 2
) q
   GROUP BY name

或者

SELECT name, 
       SUBSTRING_INDEX(so_no, ',', 1) so_no,
       CASE WHEN SUBSTRING_INDEX(SUBSTRING_INDEX(so_no, ',', 2), ',', -1) = SUBSTRING_INDEX(so_no, ',', 1)
            THEN NULL
            ELSE SUBSTRING_INDEX(SUBSTRING_INDEX(so_no, ',', 2), ',', -1)
       END prev_so_no
  FROM
(
  SELECT name, GROUP_CONCAT(so_no ORDER BY so_no DESC) so_no
    FROM table1
   WHERE name = 'Adrian'
     AND so_no <= 'SO-00005'
   GROUP BY name
) q

所有查询的输出:

|   NAME |    SO_NO | PREV_SO_NO |
|--------|----------|------------|
| Adrian | SO-00005 |   SO-00002 |
2021-07-01