Excel Power Query 如何添加新列确定最近和第二个最近日期(当前与之前)

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

我有一个数据集,其中包含带有某些字段的报告日期。我想使用 excel power query 添加一列(例如状态),确定最近的日期(例如 2022 年 3 月 1 日)并分配“当前”,以及第二个最近的日期(例如 2022 年 2 月 1 日) )并分配“优先”。任何帮助将不胜感激。谢谢!

报告日期 公司 数量 状态
2022 年 1 月 1 日 苹果 7
2022 年 1 月 1 日 HP 4
2022 年 2 月 1 日 苹果 8 之前
2022 年 2 月 1 日 HP 9 之前
2022 年 3 月 1 日 苹果 10 当前
2022 年 3 月 1 日 HP 10 当前
excel powerquery data-analysis data-cleaning m
2个回答
2
投票

给你。

let
    Source = Table.FromRows(Json.Document(Binary.Decompress(Binary.FromText("i45WMtQ31DcyMDJSUNJRciwoyEkFMcwVlGJ1UOU8AkCkCUTCCJsmC0w5iCZLiIQxNk2GBpiSEF1gmVgA", BinaryEncoding.Base64), Compression.Deflate)), let _t = ((type nullable text) meta [Serialized.Text = true]) in type table [#"Report Date" = _t, Company = _t, Number = _t]),
    #"Changed Type" = Table.TransformColumnTypes(Source,{{"Report Date", type date}, {"Company", type text}, {"Number", Int64.Type}}),
    #"Grouped Rows" = Table.Group(#"Changed Type", {"Company"}, {{"All", each _, type table [Report Date=nullable date, Company=nullable text, Number=nullable number]}}),
    #"Added Custom" = Table.AddColumn(#"Grouped Rows", "Custom", each 
        let a = Table.Sort([All], {{"Report Date", Order.Descending}}),
        b = Table.AddIndexColumn(a, "index"),
        c = Table.AddColumn(b, "Status", each if [index] = 0 then "Current" else if [index] = 1 then "Prior" else null )
        in c
        ),
    #"Removed Columns" = Table.RemoveColumns(#"Added Custom",{"Company", "All"}),
    #"Expanded Custom" = Table.ExpandTableColumn(#"Removed Columns", "Custom", {"Report Date", "Company", "Number", "index", "Status"}, {"Report Date", "Company", "Number", "index", "Status"}),
    #"Removed Columns1" = Table.RemoveColumns(#"Expanded Custom",{"index"})
in
    #"Removed Columns1"


2
投票

在 powerquery 中,尝试以下(忽略公司)

要获取报告日期列中的所有值,请使用
表格[报告日期]

对其进行排序以按日期顺序排列
List.Sort(表[报告日期],Order.降序)

由于有重复的日期,我们删除重复的
List.Distinct(List.Sort(表[报告日期],Order.降序))

那么如果你取第一行,那就是最新日期
List.Distinct(List.Sort(表[报告日期],Order.降序)){0}

该日期之前的日期是
List.Distinct(List.Sort(表[报告日期],Order.降序)){1}

然后只需添加一个自定义列,将每行上的 ReportDate 与这些列进行比较

let  Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],
#"Changed Type" = Table.TransformColumnTypes(Source,{{"Report Date", type date}, {"Company", type text}, {"Number", Int64.Type}}),
LastDate=List.Distinct(List.Sort(#"Changed Type"[Report Date], Order.Descending)){0},
NextDate=List.Distinct(List.Sort(#"Changed Type"[Report Date], Order.Descending)){1},
#"Added Custom" = Table.AddColumn(#"Changed Type", "Status", each if [Report Date]=LastDate then "Current" else if [Report Date]=NextDate then "Prior" else null)
in  #"Added Custom"
© www.soinside.com 2019 - 2024. All rights reserved.