小编den*_*kai的帖子

过滤掉SELECT中的重复后续记录

(PostgreSQL 8.4) 表"trackingMessages"存储移动设备(tm_nl_mobileid)和固定设备(tm_nl_fixedId)之间的跟踪事件.

CREATE TABLE trackingMessages
(
  tm_id SERIAL PRIMARY KEY,           -- PK
  tm_nl_mobileId INTEGER,             -- FK to mobile
  tm_nl_fixedId INTEGER,              -- FK to fixed
  tm_date INTEGER,                    -- Network time
  tm_messageType INTEGER,             -- 0=disconnect, 1=connect
  CONSTRAINT tm_unique_row
    UNIQUE (tm_nl_mobileId, tm_nl_fixedId, tm_date, tm_messageType)
);
Run Code Online (Sandbox Code Playgroud)

这里的问题是,相同的移动设备可能随后连接到相同的固定设备两次(或更多次).我不希望看到后续的那些,但是可以看到移动设备在以后固定连接到同一个固定设备,前提是它们之间存在连接到不同的固定设备.

我想我很亲密但并不完全.我一直在使用以下CTE(在Stack Overflow上找到)

WITH cte AS 
(
  SELECT tm_nl_fixedid, tm_date, Row_number() OVER (
    partition BY tm_nl_fixedid
    ORDER BY tm_date ASC
  ) RN 
  FROM   trackingMessages
) 
SELECT * FROM cte 
  WHERE tm_nl_mobileid = 150 AND tm_messagetype = 1 …
Run Code Online (Sandbox Code Playgroud)

sql postgresql window-functions gaps-and-islands

6
推荐指数
1
解决办法
1661
查看次数