Вы не можете рассчитать изменение цены для PreviousPrice
, поскольку PreviousPrice
является псевдонимом для select
подзапроса
с использованием подзапроса для создания PreviousPrice
столбца
Вы можете попробовать этот запрос.
SELECT t.*,
(t.previousprice - t.price) AS PriceDiff
FROM (
SELECT
history.partnumber,
history.datetime,
history.price,
history.quantity,
(
SELECT TOP 1 price
FROM history AS History1
WHERE History1.datetime < history.datetime
AND History1.partnumber = history.partnumber
ORDER BY History1.datetime DESC
) AS PreviousPrice
FROM history
)t
ORDER BY t.partnumber,
t.datetime DESC
Я думаю, вам нужно использовать функцию coalesce
, если ее нет PreviousPrice
.
SELECT t.partnumber,
t.datetime,
t.price,
t.quantity,
coalesce(t.PreviousPrice,0) as 'PreviousPrice',
coalesce((t.previousprice - t.price),0) AS 'PriceDiff'
FROM (
SELECT
history.partnumber,
history.datetime,
history.price,
history.quantity,
(
SELECT TOP 1 price
FROM history AS History1
WHERE History1.datetime < history.datetime
AND History1.partnumber = history.partnumber
ORDER BY History1.datetime DESC
) AS PreviousPrice
FROM history
)t
ORDER BY t.partnumber,
t.datetime DESC
sqlfiddle: http://sqlfiddle.com/#!18/52a7b/5
EDIT
В моем доступе этот запрос работает хорошо.
Если вы хотите добавить символ валюты в столбец PriceDiff
, вы можете использовать функцию Формат .
Вы можете попробовать это.
SELECT t.*,
abs(t.previousprice - t.price) AS PriceDiff
FROM (
SELECT
history.partnumber,
history.datetime,
history.price,
history.quantity,
(
SELECT TOP 1 price
FROM history AS History1
WHERE History1.datetime < history.datetime
AND History1.partnumber = history.partnumber
ORDER BY History1.datetime DESC
) AS PreviousPrice
FROM history
)t
WHERE t.PreviousPrice is not null
ORDER BY t.partnumber,
t.datetime
Исходные данные

Результат запроса

sqlfiddle: http://sqlfiddle.com/#!18/bfddb/6
EDIT # 2
Я видел ваши исходные данные. В исходных данных много дубликатов datetime
. Вы не можете использовать datetime
для сравнения в подзапросе, иначе в подзапросе будет несколько строк.
так что вы можете сравнить с ID
столбцом, потому что это ваш PK
.
вы можете использовать ID
вместо datetime
SELECT t.*,
abs(t.previousprice - t.price) AS PriceDiff
FROM (
SELECT
history.id,
history.partnumber,
history.datetime,
history.price,
history.quantity,
(
SELECT TOP 1 price
FROM history AS History1
WHERE History1.id < history.id
AND History1.partnumber = history.partnumber
ORDER BY History1.id DESC
) AS PreviousPrice
FROM history
)t
ORDER BY t.partnumber,t.id
sqlfiddle: http://sqlfiddle.com/#!18/bdeb91/1