我有一张像这样的表@ROOMS_BY_DEPA_KEY1
:
DECLARE @ROOMS_BY_DEPA_KEY1 TABLE
(
OPRO_KEY INT,
KAPACITETA INT,
WEEK_1 DECIMAL(8,2),
WEEK_2 DECIMAL(8,2),
WEEK_3 DECIMAL(8,2),
WEEK_4 DECIMAL(8,2),
WEEK_5 DECIMAL(8,2),
WEEK_6 DECIMAL(8,2)
)
INSERT INTO @ROOMS_BY_DEPA_KEY1(OPRO_KEY)
VALUES (160000014),(160000015),(160000016),(160000017),(160000018),(160000019),(160000020)
所以在填写一些数据表之后如下:
我必须使用此表中的结果更新每个行WEEK_1
,WEEK_2
,WEEK_3
,WEEK_4
,WEEK_5
,WEEK_6
,这是从OPRO_KEY
和KAPACITETA
生成的:
DECLARE @WEEKS_MONTH AS DBO.WEEKS_MONTH_Type
(
WEEKOFMONTH INT,
WEEKSTART DATE,
WEEKEND DATE,
NO_DAYS INT,
AVERAGE_AVAI DECIMAL(8,2)
)
(它的表格类型,因为它被用作函数参数)。该表的结果如下所示:
要获得第二个表,我有一个UDF:
dbo.f_SCAVAI_GetWeekAverage(@iOPRO_KEY, @WEEKS_MONTH, '1', @iKAPACITETA)
表@WEEKS_MONTH
填充了一些值(weekofmonth,datestart,dateend,no_days),每次调用都保持不变:
我的问题是如何为每个OPRO_KEY
调用此函数以及如何从返回表更新周列?
列根据WEEKOFMONTH
进行更新。示例:WEEK_1
更新@WEEK_MONTHS.WEEK_OF_MONTH
= 1,WEEK_2
其中@WEEK_MONTHS
= 2
答案 0 :(得分:1)
如果您总是有6个星期,更新@ ROOMS_BY_DEPA_KEY1表的最简单方法是使用@Weeks_Month表的轴:
UPDATE @ROOMS_BY_DEPA_KEY1
SET Week_1 = w.Week_1
,Week_2 = w.Week_2
,Week_3 = w.Week_3
,Week_4 = w.Week_4
,Week_5 = w.Week_5
,Week_6 = w.Week_6
FROM
(SELECT *
FROM (SELECT 'Week_' + CAST(WeekOfMonth AS VARCHAR) AS WeekName
,Average_Avai
FROM @WEEKS_MONTH) wm
PIVOT (MAX(Average_Avai)
FOR WeekName IN (Week_1, Week_2, Week_3, Week_4, Week_5, Week_6)
)p
) w
答案 1 :(得分:0)
我设法解决了这个问题:
UPDATE RM
SET RM.WEEK_1 = (
SELECT P.AVERAGE_AVAI FROM dbo.f_SCAVAI_GetWeekAverage(RM.DEPA_KEY, RM.OPRO_KEY, @WEEKS_MONTH, @cWorkDaysOnly, RM.KAPACITETA) P WHERE P.WEEKOFMONTH = 1
),
RM.WEEK_2 = (
SELECT P.AVERAGE_AVAI FROM dbo.f_SCAVAI_GetWeekAverage(RM.DEPA_KEY,RM.OPRO_KEY, @WEEKS_MONTH, @cWorkDaysOnly, RM.KAPACITETA) P WHERE P.WEEKOFMONTH = 2
),
RM.WEEK_3 = (
SELECT P.AVERAGE_AVAI FROM dbo.f_SCAVAI_GetWeekAverage(RM.DEPA_KEY,RM.OPRO_KEY, @WEEKS_MONTH, @cWorkDaysOnly, RM.KAPACITETA) P WHERE P.WEEKOFMONTH = 3
),
RM.WEEK_4 = (
SELECT P.AVERAGE_AVAI FROM dbo.f_SCAVAI_GetWeekAverage(RM.DEPA_KEY,RM.OPRO_KEY, @WEEKS_MONTH, @cWorkDaysOnly, RM.KAPACITETA) P WHERE P.WEEKOFMONTH = 4
),
RM.WEEK_5 = (
SELECT P.AVERAGE_AVAI FROM dbo.f_SCAVAI_GetWeekAverage(RM.DEPA_KEY,RM.OPRO_KEY, @WEEKS_MONTH, @cWorkDaysOnly, RM.KAPACITETA) P WHERE P.WEEKOFMONTH = 5
),
RM.WEEK_6 = (
SELECT P.AVERAGE_AVAI FROM dbo.f_SCAVAI_GetWeekAverage(RM.DEPA_KEY,RM.OPRO_KEY, @WEEKS_MONTH, @cWorkDaysOnly, RM.KAPACITETA) P WHERE P.WEEKOFMONTH = 6
)
FROM @ROOMS_BY_DEPA_KEY1 RM