18

I have a table that has values for quarters and I need to add a new column that gives me the last not null value as last quarter. For example

ID | Project  | Q1   | Q2   | Q3   | Q4   | Current Quarter Value  
1  | bal bal  | 23   | 32   | 34   | null | 34  
2  | cuz cuz  | 43   | 56   | null | null | 56  
pnuts
  • 58,317
  • 11
  • 87
  • 139
dev_huesca
  • 456
  • 1
  • 3
  • 14

5 Answers5

26

There are a couple formulas you can use when adding a custom column to the table (accessible from the Transform ribbon tab). Here's one:

if [Q4] <> null then [Q4] else if [Q3] <> null then [Q3] else if [Q2] <> null then [Q2] else [Q1]

If you don't want to write so many if statements, you can add the columns to a list and filter out the null values:

List.Last(List.Select({[Q1], [Q2], [Q3], [Q4]}, each _ <> null))

18

You can try the null coalescing operator (??). Both of the following lines achieve the same effect of returning ValueA unless it is null, in which case ValueB is returned.

if ValueA <> null then ValueA else ValueB
ValueA ?? ValueB

Applied to your specific case the necessary code would be:

[Q4] ?? [Q3] ?? [Q2] ?? [Q1]

Note that the null coalescing operator is a new addition to Power Query. It has not been officially documented yet and may not be available in all environments.

Information taken from this blog post.

MarioVW
  • 2,225
  • 3
  • 22
  • 28
2

It's great how the Power Query M Language has developed over time. And luckily the null coalescing operator has been introduced. It's represented by ??

The easiest way to do a COALESCE is by using the last example. But you can use any of the following methods:

= null ?? null ?? 1 ?? 2
= List.First( List.RemoveNulls( { null, null, 1, 2 } ) )
= List.First( List.RemoveFirstN( { null, null, 1, 2 }, each _ = null ) )
= List.RemoveFirstN( { null, null, 1, 2 }, each _ = null ){0}
= List.Select( { null, null, 1, 2 }, each _ <> null ){0}

More explanation on this you can find here: https://gorilla.bi/power-query/coalesce/

Cheers, Rick

0

I think is a little bit late, but I'm also looking for a better solution than: List.First( List.RemoveNulls( { list } ) )

or for a default value:

List.First( List.RemoveNulls( List.Combine { { list }, { defaultValue } } ) ) )

user682701
  • 1,441
  • 1
  • 9
  • 4
0

Using List.RemoveNulls bothered me because it seems to do more work than necessary.

Here is a function that appears to avoid processing the whole list, beyond the first non-null item:

coalesce = each List.First(List.RemoveFirstN(_, each _ = null), null)

Jared S
  • 61
  • 3