如何在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
答案 0 :(得分:4)
这个在所有主要的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 |
以下是 SQLFiddle 演示( SQL Server 2008 )更新了
这是 SQLFiddle 演示( SQL Server 2012 )
这是 SQLFiddle 演示( MySQL )
答案 1 :(得分:0)
尝试offset
,这种方式不是那么干净,但也许可以帮助你
SELECT name as "Name",
(SELECT so_no FROM table WHERE name LIKE '%Adrian%' ORDER BY so_no DESC LIMIT 1) as "SO No.",
(SELECT so_no FROM table WHERE name LIKE '%Adrian%' ORDER BY so_no DESC OFFSET 1 LIMIT 1) as "Previous SO"
FROM table
WHERE name LIKE '%Adrian%'
LIMIT 1;
抱歉查询不好,还有一些新手:(