![](/img/trans.png)
[英]Power BI how to create new column in date table based on conditions and reference to another table
[英]How to create calculated column based on attribute and date range in other table Power BI?
我有两个表,表 A 包含一个属性 (ID1) 和时间(日期/时间格式)。 表 B 包含一个属性 (ID2) 和两个时间列 Time_start 和 Time_end(均为日期/时间)格式。
我需要在表 A 中创建一个列,从表 B 中获取 ID2,其中 ID1=ID2 并且时间介于 Time_start 和 Time_end 之间。
我尝试了以下但由于数据量(TableA 中有 500 万行,TableB 中有 10 万行)我用完了 RAM:
Column = CALCULATE(FIRSTNONBLANK(TableB[ID2],1),FILTER(TableB,TableB[ID2]='TableA'[ID1]),FILTER(TableB,TableB[Time_start]<='TableA'[Time]),FILTER(TableB,TableB[Time_end]>='TableA'[Time]))
我已经在 Power Query 中应用了日期筛选器并删除了我不需要的列。 在 DAX 或 Power Query 中是否有更有效的方法来执行此操作,不幸的是,在 SQL 中的日期加载之前加入表不是一个选项。
对于您要处理的大小,您应该在 Power Query 而不是 DAX 中执行此操作。 合并 2 个表,然后展开表以获得Time_start和Time_end 。 然后使用如下公式添加ID2 :
try if [Time_start] <= [Time] and [Time] <= [Time_end] then [ID1] else null otherwise null)
try
和otherwise
将处理Time_start和Time_end中的空值,否则会导致错误。
这是我的示例查询:
// Table A
let
Source = Table.FromRows(Json.Document(Binary.Decompress(Binary.FromText("i45WclTSUTLUN9Q3MlIwtDIyVorViVZywiLmjEXMFV0sFgA=", BinaryEncoding.Base64), Compression.Deflate)), let _t = ((type nullable text) meta [Serialized.Text = true]) in type table [ID1 = _t, Time = _t]),
#"Changed Type" = Table.TransformColumnTypes(Source,{{"ID1", type text}, {"Time", type datetime}}),
#"Merged Queries" = Table.NestedJoin(#"Changed Type", {"ID1"}, #"Table B", {"ID2"}, "Table B", JoinKind.LeftOuter),
#"Expanded Table B" = Table.ExpandTableColumn(#"Merged Queries", "Table B", {"Time_start", "Time_end"}, {"Time_start", "Time_end"}),
#"Added Custom" = Table.AddColumn(#"Expanded Table B", "ID2", each try if [Time_start] <= [Time] and [Time] <= [Time_end] then [ID1] else null otherwise null),
#"Removed Columns" = Table.RemoveColumns(#"Added Custom",{"Time_start", "Time_end"})
in
#"Removed Columns"
// Table B
let
Source = Table.FromRows(Json.Document(Binary.Decompress(Binary.FromText("i45WclTSUTI00jc21DcyVDC0MjAA8cFcIwg3VidayQksiBCD84xgKpyBYkYoKozQVLhgmIGsPjYWAA==", BinaryEncoding.Base64), Compression.Deflate)), let _t = ((type nullable text) meta [Serialized.Text = true]) in type table [ID2 = _t, Time_start = _t, Time_end = _t]),
#"Changed Type" = Table.TransformColumnTypes(Source,{{"ID2", type text}, {"Time_start", type datetime}, {"Time_end", type datetime}})
in
#"Changed Type"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.