按列键更新表和摘要

时间:2017-03-10 15:45:24

标签: sql-server tsql

我有一张这样的表:

declare @rooms table
(
depa_key int,
room_key int,
d1 int,
d2 int
)

insert into @rooms(depa_key, room_key, d1, d2)
select 1, null, null, null
union all
select 1, 1, 1, 1
union all
select 1, 1, 1, 1
union all
select 2, null, null, null
union all
select 2, 1, 5, 3
union all
select 2, 1, 7, 2
union all
select 3, null, null, null
union all
select 3, 1, 6, 9
union all
select 3, 1, 5, 8

表填充有:

enter image description here

我想要做什么(但我不知道如何)填充摘要行(romm_key is null的行与depa_key的摘要。

room_key为null的行是摘要行。只有部门没有room_key(因为部门意味着所有房间)。每个房间都有room_key和depa_key。

示例:

第一行(depa_key = 1,room_key = NULL)应填充:

D1   D2
2    2

第二行(depa_key = 2,room_key = NULL)应填充:

D1   D2
12   5

将来会有很多depa_keys(表正在改变动态),因此查询也必须是动态的。 我可以逐个输入depa_keys(更新查询),但我不能这样做。如何动态地用depa_key中的摘要更新列d1和d2?

2 个答案:

答案 0 :(得分:2)

试试这个。

declare @rooms table
(
depa_key int,
room_key int,
d1 int,
d2 int
)

insert into @rooms(depa_key, room_key, d1, d2)
select 1, null, null, null
union all
select 1, 1, 1, 1
union all
select 1, 1, 1, 1
union all
select 2, null, null, null
union all
select 2, 1, 5, 3
union all
select 2, 1, 7, 2
union all
select 3, null, null, null
union all
select 3, 1, 6, 9
union all
select 3, 1, 5, 8


UPDATE @rooms
SET d1 = a.d1, d2 = a.d2
FROM (
        SELECT depa_key, SUM(D1)d1, SUM(d2) d2
        FROM @rooms
        GROUP BY depa_key
    ) a
    JOIN @rooms r ON
        a.depa_key = r.depa_key
WHERE r.room_key IS NULL


SELECT *
FROM @rooms

答案 1 :(得分:1)

CTE的解决方案看起来更具可读性。 首先,我们采用depa_key的汇总信息,仅获取room_key IS NOT NULL的房间记录。然后,我们通过此聚合数据更新room_key IS NULL的行。

;WITH DepaStats AS
(
    SELECT
        depa_key     AS depa_key,
        SUM(d1)      AS sum_d1,
        SUM(d2)      AS sum_d2
    FROM @rooms
    WHERE room_key IS NOT NULL
    GROUP BY depa_key
)
UPDATE R
SET
    d1 = S.sum_d1,
    d2 = S.sum_d2
FROM @rooms R
LEFT JOIN DepaStats S
    ON S.depa_key = R.depa_key
WHERE R.room_key IS NULL