我需要为以下内容编写SQL语句。我需要将表中的数据从一列移动到另一列,如下所示。 Prior Year
的日期需要进入前一年日期的Current Year
列。该表有1百万行。
如果日期是2017年1月1日,则位置佐治亚州,产品馏分,我的当前年度数量显示为空。这些卷作为上一年卷位于2018年1月1日的行中。所以我需要将这些卷从2018年日期移到2017年。卷100和200应该移动。
我的原始表格如下:
Date, Location, Product, PY volumes, CY Volumes
Jan 1 2017, Georgia, Gasoline, NULL, NULL
Jan 2 2017, Texas, Distillate, NULL, NULL
Jan 1 2018, Georgia, Gasoline, 100, 110
Jan 2 2018, Texas, Distillate, 200, 190
我的决赛桌应如下所示:
Date, Location, Product, PY volumes, CY Volumes
Jan 1 2017, Georgia, Gasoline, NULL, 100
Jan 2 2017, Texas, Distillate, NULL, 200
Jan 1 2018, Georgia, Gasoline, NULL, 110
Jan 2 2018, Texas, Distillate, NULL, 190
答案 0 :(得分:0)
您似乎将PY卷设置为空..如果您愿意,可以自行加入以获取下一年的价值甚至是上一年的价值
update cy
set cy.[PY volumes] = NULL, --?
cy.[CY Volumes] = ny.[PY volumes]
from dbo.Table cy -- Current Year
left join dbo.Table ny -- Next Year
on dateadd(year, 1, cy.Date) = ny.Date
and cy.Location = ny.Location --if needed
and cy.Product = ny.Product --if needed
答案 1 :(得分:0)
如果您每年执行一次而不是每小时一次,那么只需在其中使用嵌套查询。
update volumes set cy_volumes = (select py_volumes from volumes v where v.date = volumes.date + '1 year' and v.product = volumes.product and v.location = volumes.location)
但我认为你想要反过来:设置2018年的前一年而不是2017年的当前年度