尝试编写查询以使用来自同一表的数据更新表。
基本上,此表中有两种类型的数据,即预算和预测,按客户,产品,会计年度和月份划分。
数据样本如下:
CustomerCosts
CustomerNo Product FiscalYear Month DataType DataField Q R G
CU01 REG 2014 1 Budget Commission 10 2 20
CU01 REG 2014 1 Budget Warehouse 5 5 25
CU01 REG 2014 2 Budget Commission 30 1 30
CU01 REG 2014 2 Budget Warehouse 12 2 24
CU01 REG 2014 1 Forecast Commission 10 2 20
CU01 REG 2014 1 Forecast Warehouse 5 5 25
CU01 REG 2014 2 Forecast Commission 30 1 30
CU01 REG 2014 2 Forecast Warehouse 12 2 24
基本上,用户将要从一种数据类型复制到另一种数据类型。例如,将2014年预算复制到2014年预测中。
我想出了这个查询,但是虽然行数似乎很有效,但显示更新的行比应有的多。
UPDATE CustomerCosts
SET CustomerCosts.Q = f.Q,
CustomerCosts.R = f.R,
CustomerCosts.G = f.G
FROM CustomerCosts
JOIN CustomerCosts f
ON CustomerCosts.CustomerNo = f.CustomerNo AND
CustomerCosts.Product = f.Product AND
CustomerCosts.Month = f.Month AND
CustomerCosts.DataField = f.DataField
WHERE CustomerCosts.FiscalYear = 2014 AND
CustomerCosts.DataType = N'Forecast' AND
f.FiscalYear = 2014 AND
f.DataType = N'Budget'
我的查询正确吗?还是我遗漏了一些东西?
谢谢。
我对我来说还可以。但是请确保进行测试始终是个好主意。使用以下命令将表CustomerCosts复制到新的临时表中
SELECT * INTO Test_CustomerCosts FROM CustomerCosts
之后,尝试更新(更改脚本,使其可以在“测试”表上使用)并查看结果。
尝试修改您的查询以选择:
select
CustomerCosts.*, f.*
FROM CustomerCosts
JOIN CustomerCosts f ON
CustomerCosts.CustomerNo = f.CustomerNo AND
CustomerCosts.Product = f.Product AND
CustomerCosts.Month = f.Month AND
CustomerCosts.DataField = f.DataField
WHERE
CustomerCosts.FiscalYear = 2014 AND
CustomerCosts.DataType = N'Forecast' AND
f.FiscalYear = 2014 AND
f.DataType = N'Budget'
看全图。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句