Forum Discussion

Yiqian's avatar
Yiqian
Regular Visitor
2 years ago
Solved

How to combine raw table with with condition table in power query

Hello all Power BI experts,   Here I have a problem and I hope I can solve it with Power Query or power BI DAX. I have two tables. One is raw data, that is like below,   Category Value a ...
  • dufoq3's avatar
    dufoq3
    2 years ago

    Check this:

     

    Output

    let
        Source = Table.FromRows(Json.Document(Binary.Decompress(Binary.FromText("i45WCs/ILM6uVNJRciwoyEkF0oYGBkqxOkgSTol5QAhkGKHL+Bcl5qWD9BhDZdwz85BMMjJFFkUohgoHZ6QWFaFYALMaLhOQmZcIMwwkFwsA", BinaryEncoding.Base64), Compression.Deflate)), let _t = ((type nullable text) meta [Serialized.Text = true]) in type table [#"Customer Name" = _t, Brand = _t, #"Sales volume" = _t]),
        ChangedType = Table.TransformColumnTypes(Source,{{"Sales volume", type number}}),
        Buffered = Table.Buffer(ChangedType),
        ConditionTable = Table.FromRows(Json.Document(Binary.Decompress(Binary.FromText("i45WCs/ILM6uVNJRciwoyElV0FZwSswDQoVHnUsVjAwMkCT8ixLz0lPBEiYoElAdKCrMgSpidaKV3DPzgCqRJIxMcZhpBpbIK83JAWsMzkgtKgK5C8k9hgZwJTCVsQA=", BinaryEncoding.Base64), Compression.Deflate)), let _t = ((type nullable text) meta [Serialized.Text = true]) in type table [#"Customer Name" = _t, #"Condition 1" = _t, #"Condition 2" = _t, #"Condition 3" = _t]),
        // You can probably delete this step.
        ReplaceTextNulls = Table.TransformColumns(ConditionTable, {}, each if _ = "null" then null else _),
        ReplacedValue = List.Accumulate(
            { {"≥", ">="}, {"≤", "<="} },
            ReplaceTextNulls, 
            (s,c)=> Table.ReplaceValue(s, c{0}, c{1}, Replacer.ReplaceText, Table.ColumnNames(s))
        ),
        Helper = [ conditionColumns = List.Select(Table.ColumnNames(ReplacedValue), (x)=> Text.StartsWith(x, "Condition", Comparer.OrdinalIgnoreCase)),
        delimiters = Text.ToList("+-/*><= ") ],
        StepBack = ReplacedValue,
        Ad_CheckColumns = List.Accumulate(
            Helper[conditionColumns],
            StepBack,
            (state, current)=> Table.AddColumn(state, current & " Check", each
                      [ a = Splitter.SplitTextByCharacterTransition((x)=> List.Contains(Helper[delimiters], x), (y)=> List.Contains(Helper[delimiters], y))(Record.Field(_, current)),
                        b = List.Transform(a, (x)=> [value = Table.SelectRows(Buffered, (y)=> y[Brand] = Text.Trim(x) and y[Customer Name] = [Customer Name]){0}?[Sales volume]?, result = if value = null then x else Text.From(value)][result]),
                        c = try Expression.Evaluate(Text.Combine(b)) otherwise null
                      ][c], type logical) ),
        UnpivotedOtherColumns = Table.UnpivotOtherColumns(Ad_CheckColumns, {"Customer Name"}, "Attribute", "Value"),
        FilteredRows = Table.SelectRows(UnpivotedOtherColumns, each Text.EndsWith([Attribute], "Check"))
    in
        FilteredRows