2

如何在 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
4

2 回答 2

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 服务器:

根据您的评论更新

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 )

于 2013-09-09T04:56:16.310 回答
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;

抱歉查询不好,也是新手:(

于 2013-09-09T04:38:37.407 回答