这个在所有主要的 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 服务器:
根据您的评论更新
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
所有查询的输出:
| 姓名 | SO_NO | PREV_SO_NO |
|--------|----------|------------|
| 阿德里安 | SO-00005 | SO-00002 |
这是SQLFiddle演示 ( SQL Server 2008 ) 更新
这是SQLFiddle演示 ( SQL Server 2012 )
这是SQLFiddle演示 ( MySQL )