在列中填充零值,下一个值大于零

时间:2018-01-31 13:44:25

标签: postgresql

我有以下Postres代码:

SELECT
a.assessmentid,
b.groupid
FROM wo_assessment a
LEFT JOIN wo_group_info b ON a.assessmentid = b.assessmentid
WHERE a.workorderid=2
ORDER BY a.assessmentid

返回以下结果:

 |-------------------|------------|
 |    assessmentid   |   groupid  |
 |-------------------|------------|                 
 |         5         |      5     |  
 |-------------------|------------|                 
 |         6         |      4     |
 |-------------------|------------|
 |         7         |      0     |
 |-------------------|------------|                 
 |         8         |      5     |
 |-------------------|------------|
 |         9         |      0     |
 |-------------------|------------|                 
 |        10         |      0     |
 |-------------------|------------|

我想用groupid字段中的0值填充该列中的下一个数字,即不是0.

所以例如我希望我的表看起来像这样:

 |-------------------|------------|
 |    assessmentid   |   groupid  |
 |-------------------|------------|                 
 |         5         |      5     |  
 |-------------------|------------|                 
 |         6         |      4     |
 |-------------------|------------|
 |         7         |      4     |
 |-------------------|------------|                 
 |         8         |      5     |
 |-------------------|------------|
 |         9         |      5     |
 |-------------------|------------|                 
 |        10         |      5     |
 |-------------------|------------|

1 个答案:

答案 0 :(得分:0)

这对我有用:

SELECT q.assessmentid, 
first_value(b.groupid ) over (partition by value_partition order by q.assessmentid) FROM (
 SELECT a.assessmentid,
    b.groupid ,
    sum(case when b.groupid is null then 0 else 1 end) over (order by a.assessmentid) as value_partition
FROM wo_assessment as a
LEFT JOIN wo_group_info b ON a.assessmentid = b.assessmentid
ORDER BY  a.assessmentid ) as q
LEFT JOIN wo_group_info b ON q.assessmentid = b.assessmentid