用于生成日期列表的函数

时间:2016-12-29 22:03:02

标签: powerquery

如何生成几年之间所有日期的列表?

这需要通过按日期过滤此类表并应用每日(每月)折旧来计算每天或每月或每年的折旧。

2 个答案:

答案 0 :(得分:1)

您可以使用List.Dates(以日期开头,计为数字,步数作为持续时间)。

例如List.Dates(#date(2016,1,1),366,#duration(1,0,0,0))为您提供2016年的所有日期。

答案 1 :(得分:0)

我创建了一个生成这样一个表的函数。它将开始和结束年份作为参数。

您可以将其作为单独的查询放置,稍后再调用,也可以完全包含在查询中。

let
    GenerateDates = (StartYear as number, EndYear as number) =>

    let
        //Generate a list of years
        Yrs = #table(type table [J = Int64.Type, Yr = Int64.Type], List.Transform({StartYear..EndYear}, each {1, _})),
        //Generate a list of months
        Mnths = #table(type table [J = Int64.Type, Mn = Int64.Type], List.Transform({1..12}, each {1, _})),
        //Generate a list of days
        Days = #table(type table [J = Int64.Type, D = Int64.Type], List.Transform({1..31}, each {1, _})),
        //Join all these tables
        Join1 = Table.Join(Yrs, "J", Mnths, "J", JoinKind.Inner),
        Join2 = Table.Join(Join1, "J", Days, "J", JoinKind.Inner),
        // Add column with date, using try..otherwise to evade errors for non-existing dates, such as 31 april. :)
        AddDate = Table.AddColumn(Join2, "Date", each try #date([Yr], [Mn], [D]) otherwise null, type date),
        //Get rid of nulls
        FilterNulls = Table.SelectRows(AddDate, each [Date] <> null),
        //Return result
        Result = Table.SelectColumns(FilterNulls, {"Date"})
    in
        Result
in
    GenerateDates

<强>更新

虽然正如MarcelBeug所说,使用List.Dates(我已经错过了:)更容易,但这里有一些使用type table可能有用的例子。