你需要做的比较复杂,但我的解决方案总结是:
- 计算每日消耗量
- 计算每次阅读的开始和结束日期(例如上一次阅读日期加一天,以及阅读日期)
- 将数据扩展为每天 1 行,而不是每次读数 1 行
您希望在将数据加载到数据模型之前(即在源系统中,或在使用查询编辑器/Power Query 加载数据时)执行这些步骤。
下面,我假设您使用的是查询编辑器/Power Query。但是,如果您可以使用您的源系统,它通常是更好的选择(因为源系统可能是一个比您的桌面快得多的数据库)。
请注意,您的天数计算对我来说没有意义。从 2016 年 1 月 24 日到 2016 年 3 月 31 日之间有超过 38 天。在 1 月 10 日到 1 月 24 日之间也有超过 13 天。因此,很难判断您是否要在当天计算新读数之前的读数是被读取的,或者是在接下来的一整天。我假设前者。另请注意,我是在您的天数计算正确的基础上继续进行的
计算每日消耗量
这是最简单的步骤,因为您已经计算了消耗量和天数。只需将一个除以另一个。在查询编辑器中,您可以单击消耗(加仑)列并选择添加列 > 标准 > 划分。在值下,选择在列中使用值,然后选择“天数”列。
计算每次阅读的开始和结束日期
读数的日期是结束日期,因此您可以将 Date 重命名为 End Date(因为读数是追溯应用的)。
对于开始日期,您需要在查询编辑器中添加一个索引列(添加列 > 索引列)。您需要确保您的数据按仪表 ID 和升序日期排序在此之前。调用列索引。
接下来,添加列 > 自定义列并从前一行中提取阅读日期。现在调用新列Previous End Date。
// A try is necessary because we can't get the previous row if there is no previous row (we'll get an error, which we can handle in the 'otherwise' block)
try
if
// See if the previous row is for the same Meter ID
[Meter ID] = #"Reordered Columns"{[Index] - 1}[Meter ID]
then
// If it is, grab the Reading Date from the previous row
#"Reordered Columns"{[Index]-1}[End Date]
else
// If this is the first reading for a meter, calculate the Start Date by subtracting the No. of Days from the End Date
Date.AddDays([End Date], -[No. of Days])
otherwise
// If this is the first row in the table, also calculate the Start Date by subtracting the No. of Days from the End Date
Date.AddDays([End Date], -[No. of Days])
接下来,您需要将 1 添加到开始日期,因为我们希望读数适用于上一次读数后的第二天,而不是上一次读数的当天。
请注意,如果您希望阅读日期计入上一周期,请从结束日期减去 1,而不是在开始日期(上一个结束日期)上加 1。
将您的数据扩展为每天 1 行
此时,您应该有一个计量器 ID、开始日期、结束日期和反映您预期的每日消耗量列(即日期范围内的每日消耗量是正确的)。
最后一步是复制日期范围内每个日期的每一行。此线程 (https://community.powerbi.com/t5/Desktop/Convert-date-ranges-into-list-of-dates/td-p/129418) 中概述了几个解决方案,但我个人推荐 MarcelBeug (https://youtu.be/QSXzhb-EwHM) 发布的技术(和视频)。
您最终应该得到更像这样的东西(在删除和重命名列之后):
终于
现在您每米和日期有一行,并且已经计算了每天的消耗量,您可以构建一个视觉对象。例如,您可以制作一个柱形图,其中 Date 在轴上,Consumption per Day 作为值。默认情况下,Power BI 将识别 Date 是一个日期,并将按年-季-月-日累计。按年和季度的小“x”,你会得到一个图表,按月总结每天的消费。您还可以向下钻取到单个日期。
进一步阅读
- Reading a value from a previous row in Power Query
- If Statements in Power Query
- The AddDays function in Power Query
- Adding Comments in Power Query
- Catching Errors in Power Query
-
Converting a date range into a list of dates(Marcel Beug 的解决方案)
- A similar problem I previously answered