1

我有下表:

row_date    logid   type    Interval   availtime    avail_distribution
9/25/2013    122     4       850         640            NULL
9/25/2013    122     5       850         0              NULL
9/25/2013    122     7       850         0              NULL
9/26/2013    122     4       850         500            NULL
9/26/2013    122     5       850         0              NULL
9/26/2013    122     7       850         0              NULL

这里的每一个avail_distribution都是由 的平均值来更新的availtime, group by row_date,logid and Interval

更新后所需的表:

row_date    logid   type    Interval   availtime    avail_distribution
9/25/2013   122      4        850        640            213.3333
9/25/2013   122      5        850        0              213.3333
9/25/2013   122      7        850        0              213.3333
9/26/2013   122      4        850        500            167.66667
9/26/2013   122      5        850        0              167.66667
9/26/2013   122      7       850         0              167.66667

Select sum(availtime)/count(availtime) 
 from table 
 group by row_date,logid,Interval; 

给了我我正在寻找的价值观..但我无法avail_distribution按照我的意图更新列。

4

3 回答 3

2

使用 CTE(公用表表达式)将允许您在进行实际更新之前轻松执行所需的任何分组/逻辑。

;WITH cte_update as (
    Select 
        row_date,
        logid,
        Interval,
        sum(availtime)/count(availtime) as avail_dist
    from 
        table 
    group by 
        row_date,
        logid,
        Interval )

update t
set 
    t.avail_distribution = cte.avail_dist
from 
    table as t
    inner join cte_update as cte 
        on t.row_date = cte.row_date 
        and t.logid = cte.logid 
        and t.interval = cte.interval
于 2013-09-27T15:19:10.720 回答
0

这可能会奏效。

UPDATE a
SET a.avail_distribution = b.val
FROM TableName a INNER JOIN
    ( Select  row_date,logid,Interval,
            sum(availtime)/count(availtime) val
    from  [Table] group by row_date,logid,Interval
    ) b ON a.row_date = b.row_date AND
        a.logid = b.logid AND
        a.Interval = c.Interval

但是为什么要这样存储数据呢?从长远来看,您将始终执行此脚本来更新列,这有点开销。

于 2013-09-27T15:19:57.410 回答
0

更新此数据的另一种方法...

Declare @Data Table
(
    row_date datetime,
    logid int,
    type int,
    Interval int,
    availtime float,
    avail_distribution float
);

Insert Into @Data(row_date,logid,type,Interval,availtime) Values 
('9/25/2013', 122, 4, 850, 640),
('9/25/2013', 122, 5, 850, 0),
('9/25/2013', 122, 7, 850, 0),
('9/26/2013', 122, 4, 850, 500),
('9/26/2013', 122, 5, 850, 0),
('9/26/2013', 122, 7, 850, 0);


;WITH CTE
as
(
    Select *, Avg(availtime) Over (partition by row_date,logid,Interval) 
    as value_of_avail_distribution from @Data
)
Update CTE Set avail_distribution = value_of_avail_distribution

select * from @Data
于 2013-09-27T15:32:03.050 回答