Power BI 和 R 中的关系数据具有来自多个字段的主键

Relational data in Power BI and R with a primary key from multiple fields

背景:

这个问题可能有点宽泛,但希望任何使用关系数据、R、Power BI 或以上所有工具的人都会感兴趣。

我正在尝试为 Wickham and GrolemundR for Data Science 一书中描述的数据集 nycflights13 重新创建一个关系模型。我正在尝试使用 R 和 Power BI 来做到这一点。该数据集由 5 tables airlinesariportsflightsweatherplanes 组成。在 13.2 nycflights13 部分中有一段指出:

flights connects to weather via origin (the location), and year, month, day and hour (the time).

关系如下图所示:

问题 1:如何在 Power BI 中设置此模型?

使用以下 R 脚本将使数据集可用于文件夹 c:/data:

中的 Power BI
# install.packages("tidyverse")
# install.packages("nycflights13")

library(tidyverse)
library(nycflights13)
setwd("C:/data/")
#getwd()

airlines
df_airlines <- data.frame(airlines)
df_airports <- data.frame(airports)
df_planes <- data.frame(planes)
df_weather <- data.frame(weather)
df_flights <- data.frame(flights)

write.csv(df_airlines, file = "C:/data/airlines.txt", row.names = FALSE)
write.csv(df_airports, file = "C:/data/airports.txt", row.names = FALSE)
write.csv(df_planes, file = "C:/data/planes.txt", row.names = FALSE)
write.csv(df_weather, file = "C:/data/weather.txt", row.names = FALSE)
write.csv(df_flights, file = "C:/data/flights.txt", row.names = FALSE)

在 Power BI 中导入 tables 后,我试图在 Relationships tab:

中建立关系

我可以在某种程度上这样做,但是当我尝试使用 yearflights 连接到 weather 时,出现以下错误留言:

You can't create a relationship between these two columsn because one of the columns must have unique values.

我知道这是因为 primary keys must contain unique values and cannot contain null values。但是如何在power BI中建立由多个字段组成的主键?

问题 2:如果问题 1 没有答案,您如何在 R 中执行此操作?

我真的很喜欢这本书,甚至可能已经在那里描述过了,但是你如何在 R 中建立这样的关系?或者也许你不需要,因为你可以 join on multiple columns or composite key using dplyr 而根本没有 'established' 关系?

换句话说,上图带箭头的关系是不是:

并在 Power BI 中使用以下行:

在 R 中真的没有必要,只要你有所需的 verbs 并且不同 table 中的数据之间确实存在关系?

问题3-为什么flight在flights中高亮table:

我认为突出显示的列名称表明已经在使用该列的 table 之间建立了联系。但据我所知,这里不是这种情况,也没有指向它的箭头:

是否可能表明它是 flights table 中的主键,与另一个 table 没有任何联系?


我知道这有点宽泛,但我真的对这些东西很好奇,所以我希望你们中的一些人会觉得它有趣!

我可以评论 Power BI 部分。

这里的关键问题是 Power BI 需要维度模型,而不是关系模型。这是个很大的差异。

如前所述,书中的模型不适合tableBI工具,必须重新设计。例如table"Weather"在书上表现为"dimension",而现实中一定是事实table(类似于table"Flights").因此,"Flights" 和 "Weather" 永远不应该有直接联系——它们必须共享共同的维度,例如:

  • 机场
  • 航空公司
  • 平面
  • 日期
  • 时间

类似地,table 之间的多个键和多个连接是非常罕见的例外并且不受欢迎(通常,它们是设计错误的迹象)。在一个设计得当的模型中,你不应该看到它们。

如果你想更深入地了解这个问题,请阅读这本书: Star Schema Complete Reference

具体回答您的问题 3,在维度建模中 "Flight"(我假设它是航班号)称为 "degenerate dimension"。通常,它应该是维度 table 的键,但如果它不存在,它将作为孤立键保留在事实 table 中。这种情况对于订单号、发票号等很常见。

Degenerate dimensions

总体而言,您的方向是正确的 - 如果您弄清楚如何将书中的模型转换为适当的星型模式,然后在 R 和 PowerBI 中使用它,您会对新功能印象深刻 -这很值得。