我有一个表Temp,Date作为主键 - 每天一行,大约2年的行。我想将8/1/2017的CY实际卷复制到9/1/2017,依此类推8月份(尽管我希望能够运行此SQL,但仍保持这个问题的简单性)也复制其他数据)。
因此,9/1/2017应该有200,等等整个月。
Date, Pipeline, CY Actual Volume
8/1/2017, XX, 200
8/2/2017, YY, 100
.....
9/1/2017, XX, 0
9/2/2017, YY, 0
.
.
我有以下SQL,但它不能正常运行(它确实运行并且给了我受影响的行数,但没有任何变化)。
update cy
set cy.[CY Actual Volume] = ny.[CY Actual Volume]
from [dbo].[Temp] cy
left join [dbo].[Temp] ny on dateadd(day, 31, cy.Date) = ny.Date
and cy.[Pipeline] = ny.[Pipeline]
where cy.[CY Actual Volume] = 0
and year(ny.Date) = 2017
答案 0 :(得分:0)
试试这个
DECLARE @temp TABLE (myDate DATETIME, pipeline VARCHAR(2), cy INT)
INSERT INTO @temp( myDate, pipeline, cy )VALUES ( '2017-08-01', 'XX', 200 )
INSERT INTO @temp( myDate, pipeline, cy )VALUES ( '2017-08-02', 'YY', 100 )
DECLARE @target TABLE (myDate DATETIME, pipeline VARCHAR(2), cy INT)
INSERT INTO @target( myDate, pipeline, cy )VALUES ( '2017-09-01', 'XX', 0 )
INSERT INTO @target( myDate, pipeline, cy )VALUES ( '2017-09-02', 'YY', 0 )
UPDATE @target SET cy = [@temp].cy FROM @temp WHERE DATEADD(MONTH,-1, [@target].myDate) = [@temp].myDate
SELECT * FROM @temp
SELECT * FROM @target
答案 1 :(得分:0)
CREATE TABLE Volume
(
Date date not null primary key,
Pipeline nvarchar(50) not null,
CY int not null
)
go
--delete Volume;
insert into Volume
(Date, Pipeline, CY)
VALUES
('2017-08-01', 'XX', 200),
('2017-08-02', 'YY', 100),
('2017-09-01', 'XX', 0),
('2017-09-02', 'YY', 0);
update v1
set
v1.CY = v2.CY
output inserted.Date, inserted.Pipeline, deleted.CY as OldCY, inserted.CY as NewCY
from
Volume as v1 inner join Volume as v2
on (DATEADD(MONTH, -1, v1.Date) = v2.Date and MONTH(v2.Date) = 8 and YEAR(v2.Date) = 2017)