使用LEAD
功能
;WITH cte
AS (SELECT *,
Lead(cpo, 2)OVER(ORDER BY dates) AS next_val
FROM (VALUES ('2016-08-01',7146,75187),
('2016-08-02',7299,68925),
('2016-08-03',7330,65534),
('2016-08-04',7416,72133),
('2016-08-05',7563,71442)) tc(dates, cpo, production_ms))
SELECT dates,
cpo,
production_ms,
production_ms * next_val
FROM cte
結果:
╔════════════╦══════╦═══════════════╦═════════════════╗
║ dates ║ cpo ║ production_ms ║ cpo_sell_profit ║
╠════════════╬══════╬═══════════════╬═════════════════╣
║ 2016-08-01 ║ 7146 ║ 75187 ║ 551120710 ║
║ 2016-08-02 ║ 7299 ║ 68925 ║ 511147800 ║
║ 2016-08-03 ║ 7330 ║ 65534 ║ 495633642 ║
║ 2016-08-04 ║ 7416 ║ 72133 ║ NULL ║
║ 2016-08-05 ║ 7563 ║ 71442 ║ NULL ║
╚════════════╩══════╩═══════════════╩═════════════════╝
如果你想相同的值時,有一個production_ms
沒有2個+日期,然後使用ISNULL
SELECT dates,
cpo,
production_ms,
production_ms * ISNULL(next_val,1)
FROM cte
結果:
╔════════════╦══════╦═══════════════╦═════════════════╗
║ dates ║ cpo ║ production_ms ║ cpo_sell_profit ║
╠════════════╬══════╬═══════════════╬═════════════════╣
║ 2016-08-01 ║ 7146 ║ 75187 ║ 551120710 ║
║ 2016-08-02 ║ 7299 ║ 68925 ║ 511147800 ║
║ 2016-08-03 ║ 7330 ║ 65534 ║ 495633642 ║
║ 2016-08-04 ║ 7416 ║ 72133 ║ 72133 ║
║ 2016-08-05 ║ 7563 ║ 71442 ║ 71442 ║
╚════════════╩══════╩═══════════════╩═════════════════╝
如果您使用您正在使用的SQL Server版本標記問題,這將有所幫助。 LAG/LEAD可能在這裏派上用場,但它們僅在2012年推出。 –
您正在使用的是哪個版本的sql server –
目前我正在使用sql server 2014 sir – Jsnow