SSIS替换字符串为中位数

时间:2013-12-19 23:05:38

标签: ssis

我有一个带数字和一些字符串的列。我打算用数值的平均值替换字符串。我怎么能这样做?

示例:

1 4
2 6
3 NA
4 10
5 NA
6 10
7 5

行号= 5 平均= 7

结果:

1 4
2 6
3 7
4 10
5 7
6 10
7 5

1 个答案:

答案 0 :(得分:0)

使用派生列将NA替换为null。将数据存储在临时表中,两个字段都作为int数据类型。你的舞台将是这样的。请确保您的数据库中没有名为Med的表格!!

BEGIN TRAN
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Med]') AND type in (N'U'))
DROP TABLE [dbo].[Med]

CREATE TABLE [dbo].[Med](
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [Val] [int] NULL
) ON [PRIMARY]

INSERT INTO [dbo].[Med] ([Val])
VALUES (4), (6), (null), (10), (null), (10), (5);   


SELECT * FROM Med;

DECLARE @Average as int; ----- Choose the right data type to meet your requirement

SELECT @Average = AVG (VAL) FROM Med;

/* Replace Update with Merge to make it more efficient
Update MED
SET Val = 
CASE 
    WHEN Val IS NULL THEN @Average
    ELSE Val
END
*/

MERGE MED as TARGET
USING
(
    SELECT ID FROM MED WHERE Val IS NULL
)
AS SOURCE ON SOURCE.ID = TARGET.ID

WHEN MATCHED THEN
UPDATE 
    SET TARGET.Val = @Average
;

SELECT * FROM Med

ROLLBACK

GO