我正在编写一个跟踪各种项目视图的应用程序,我遇到了一些障碍。我需要在两个相邻更新之间获得不同的视图。更新由UNIQUE
密钥标识,其中包含time
和id
列。如果不运行多个查询,我怎么能这样做?
SELECT updates.views, (updates.views - <previous views>)
FROM updates JOIN stuff ON stuff.id = stuff.id
WHERE updates.time = '01-01-1970 00:00:00' AND stuff.owner = 'someone'
答案 0 :(得分:2)
这几乎适用于任何RDBMS:
SELECT
UPD.id,
UPD.views,
(UPD.views - COALESCE(LAST_UPD.views, 0))
FROM
Updates UPD
INNER JOIN Stuff S ON
S.id = UPD.id AND
S.owner = 'someone'
INNER JOIN Updates LAST_UPD ON
LAST_UPD.id = UPD.id AND
LAST_UPD.time < UPD.time
LEFT OUTER JOIN Updates UPD2 ON
UPD2.id = LAST_UPD.id AND
UPD2.time < UPD.time AND
UPD2.time > LAST_UPD.time
WHERE
UPD2.id IS NULL AND
UPD.time = '01-01-1970 00:00:00'
你基本上做的是说:“给我一个之前的更新(LAST_UPD.time&lt; UPD.time),在此之后和之前没有其他更新(左连接和UPD2.id IS) NULL)。
答案 1 :(得分:1)
您可以在子查询中选择以前的最大值:
SELECT updates.views
, (updates.views - (
select max(prevupd.views)
from updates prevupd
where prevupd.id <> updates.id
))
FROM updates
JOIN stuff ON stuff.id = stuff.id
WHERE updates.time = '01-01-1970 00:00:00'
AND stuff.owner = 'someone'
一些示例数据会很好,正如Larry Lustig建议的那样。
答案 2 :(得分:1)
在Oracle
和PostgreSQL 8.4
:
SELECT views - LAG(views) OVER (ORDER BY time, id)
FROM updates
JOIN stuff
ON stuff.id = updates.stuffid
WHERE updates.time = '01-01-1970 00:00:00'
AND stuff.owner = 'someone'
在MySQL
:
SELECT views - @pviews AS diff,
@pviews := views
FROM (
SELECT @pviews := NULL
) vars
CROSS JOIN
updates
JOIN stuff
ON stuff.id = updates.stuffid
WHERE updates.time = '01-01-1970 00:00:00'
AND stuff.owner = 'someone'
ORDER BY
time, id