SQL:在一行中获取多行条目(来自同一个表)?

时间:2016-02-23 11:13:19

标签: sql sybase

我已经看过可能有我答案的问题,但没有人真的这样:

我有一张这样的表:

id | timestamp | date       | identifier | personnel_number
00 | 00000     | 2000-01-01 | A          | 01
01 | 28800     | 2000-01-01 | B          | 01
02 | 29000     | 2000-01-01 | A          | 01
03 | 45000     | 2000-01-01 | B          | 01
.
.
.

我需要结果(在这种情况下,所有四条实线)的行数的一半(在标识符A和B之间交替)。我已经尝试过了:

SELECT DISTINCT
     a.timestamp,
     b.timestamp
FROM table AS a
LEFT JOIN table AS b
     ON a.personnel_number = b.personnel_number
     AND a.date = b.date
     AND a.identifier != b.identifier
WHERE a.personnel_number = [SOMEVALUE]
     AND a.date = [SOMEDATE]
     AND a.identifier = "A"
     AND a.id > b.id
     AND a.timestamp < b.timestamp
GROUP BY a.timestamp, b.timestamp
ORDER BY a.timestamp ASC

但这并没有给我所需的两行与

a.timestamp#1, b.timestamp#1
a.timestamp#2, b.timestamp#2

但是给了我

a.timestamp#1, b.timestamp#1
a.timestamp#1, b.timestamp#2
a.timestamp#2, b.timestamp#2

我用另一种方式错误地使用MIN(显然是错误的方式)。认为这是对的,因为只有两个结果。

SELECT DISTINCT
     a.timestamp,
     MIN(b.timestamp)
FROM table AS a,
     table AS b
WHERE a.personnel_number=[SOMEVALUE]
     AND b.personnel_number=[SOMEVALUE]
     AND a.date=[SOMEDATE]
     AND b.date=[SOMEDATE]
     AND a.identifier = "A"
     AND b.identifier = "B"
     AND b.id > a.id
GROUP BY a.timestamp
ORDER BY a.timestamp ASC

我的结果是这样的,所以显然不正确^^°

a.timestamp#1, b.timestamp#1
a.timestamp#2, b.timestamp#1

根本想知道如何获得我需要的结果,当然还有更多表条目的结果?

编辑:至于回答这个问题,我使用的是Sybase。

1 个答案:

答案 0 :(得分:0)

可以使用更大的测试数据集,但这应该指向正确的方向:

编辑 - 使用LAG功能的完全修订方法

测试数据:

CREATE TABLE times
    ([id] int, [timestamp] int, [date] datetime, [identifier] varchar(1), [personnel_number] int)
;

INSERT INTO times
    (id, [timestamp], [date], identifier, personnel_number)
VALUES
    (00, 00000, '2000-01-01 00:00:00', 'A', 01),
    (01, 28800, '2000-01-01 00:00:00', 'B', 01),
    (02, 29000, '2000-01-01 00:00:00', 'A', 01),
    (03, 45000, '2000-01-01 00:00:00', 'B', 01),
    (04, 36000, '2000-01-01 00:00:00', 'A', 02),
    (05, 55000, '2000-01-01 00:00:00', 'B', 02);

查询:

SELECT a.personnel_number, a.timestamp AS timestampa, b.timestamp AS timestampb
  FROM(SELECT id
            , [timestamp]
            , [date]
            , identifier
            , personnel_number
         FROM times) AS a
  JOIN(SELECT id
            , [timestamp]
            , LAG(id) OVER (ORDER BY personnel_number, [date], [timestamp]) AS previd
            , LAG([timestamp]) OVER (ORDER BY personnel_number, [date], [timestamp]) AS prevtimestamp
            , [date]
            , identifier
            , personnel_number
         FROM times) AS b
    ON b.prevtimestamp = a.timestamp  
   AND b.personnel_number = a.personnel_number 
   AND b.date = a.date

<强>结果:

personnel_number    timestampa  timestampb
1                   0           28800
1                   28800       29000
1                   29000       45000
2                   36000       55000