将空值替换为列中的值

问题描述 投票:0回答:1

如果偏移和持续时间列中同时存在null和数值,我想用星期一至星期日的特定设置的那个null值替换该数值。

laboraccountid | weekday   | offset | duration
---------------+-----------+--------+---------
190685         | Monday    | 200    | 500
190685         | Tuesday   | 200    | 500
190685         | Wednesday | null   | null
190685         | Thursday  | null   | null
190685         | Friday    | 200    | 500
190685         | Sunday    | 200    | 500
125686         | Monday    | 1435   | 5687
125686         | Tuesday   | 1435   | 5687
125686         | Wednesday | 1435   | 5687
125686         | Thursday  | 1435   | 5687
125686         | Friday    | 1435   | 5687
125686         | Saturday  | 1435   | 5687
125686         | Sunday    | 1435   | 5687

我尝试使用case语句,但无法执行。

sql sql-server
1个回答
0
投票

您可以尝试类似的操作,添加CTE以获取按帐户ID分组的替换NULL值。:

WITH BestValue
AS
(
SELECT
    laboraccountid,
    MAX(offset) AS offset,
    MAX(duration) AS duration
FROM
    MyTable
WHERE
    offset IS NOT NULL AND duration IS NOT NULL
GROUP BY
    laboraccountid
)
SELECT
    laboraccountid,
    weekday,
    ISNULL(offset,BV.offset) as offset,
    ISNULL(duration, BV.duration) as duration
FROM
    MyTable AS MT
    JOIN
    BestValue AS BV
    ON MT.laboraccountid = BV.laboraccountid

这将为您提供当周的最大值作为NULL的替代物。

这假设每周至少有一个非空值。

case等于

    CASE
        WHEN offset IS NULL THEN BV.offset
        ELSE offset
    END AS offset,
    ....
© www.soinside.com 2019 - 2024. All rights reserved.