0

If there is both null and numeric value in the offset and duration columns, I want to replace that null value with that numeric value for that particular set Monday to Sunday.

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

I tried using the case statement but I am unable to do it.

3
  • 1
    SO is about helping you, not doing it for you, so have a go and see how far you can get. Commented Jan 21, 2020 at 20:08
  • Look into coalesce function. Commented Jan 21, 2020 at 20:11
  • 1
    Adding your desired result set will help to clarify your question. Commented Jan 21, 2020 at 20:48

1 Answer 1

1

You could try something like, adding a CTE to get the replacement NULL values grouped by the account id.:

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
    MT.laboraccountid,
    MT.weekday,
    ISNULL(MT.offset,BV.offset) as offset,
    ISNULL(MT.duration, BV.duration) as duration
FROM
    MyTable AS MT
    JOIN
    BestValue AS BV
    ON MT.laboraccountid = BV.laboraccountid

This will give you the maximum value for that week as the NULL replacement.

This assumes that there is at least one non-null value for each week.

The case equivalent is

    CASE
        WHEN offset IS NULL THEN BV.offset
        ELSE offset
    END AS MT.offset,
    ....
Sign up to request clarification or add additional context in comments.

7 Comments

I think isnull function will not work because I am trying to replace the null with the values in the set from Monday to Sunday in that set it is 200 and 500 what if the other set have different values
I am sure that it will. Why do you think it won't? Try it.
i tried the case statement it is replacing every null in the column to 200 but i want to replace depends on the laboraccountid
Please give your required results. Do you mean that you want to use the values for that week. Please clarify what it is that you want.
i want to replace the null values with the values for that particular week associated with the labor account
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.