简体   繁体   English

通过 Power BI (DAX) 中的多对一关系从相关表中返回汇总值

[英]Return a summarized value from a related table via a many to one relationship in Power BI (DAX)

I'm working with PowerBI, but considering this is a Dax question I'd assume this applies to power pivot as well.我正在使用 PowerBI,但考虑到这是一个 Dax 问题,我认为这也适用于 power pivot。

Consider the following tables, with the desired result in Table - One:考虑下表,在表一中得到所需的结果:

Table - Many表 - 许多

+----+-------+
| id | value |
+----+-------+
| 1  | a     |
+----+-------+
| 1  | a     |
+----+-------+
| 1  | a     |
+----+-------+

Table - One表 - 一

+----+-----------------------+
| id | minValueFromTableMany |
+----+-----------------------+
| 1  | (Expecting a)         |
+----+-----------------------+

I have a relationship setup between the two tables.我在两个表之间建立了关系。 I'd like to derive a new attribute in 'Table - One' that is simply the min on 'value' in table - many for each matching id.我想在“表 - 一个”中派生一个新属性,它只是表中“值”的最小值 - 每个匹配的 id 都有很多。

This would be trivial in any SQL-varient, Python or R.这在任何 SQL 变体、Python 或 R 中都是微不足道的。

SQL SQL

SELECT
    T1.id
    ,T2.minValueFromTableMany
FROM TableOne T1
    INNER JOIN ( 
                 SELECT MIN(value) as minValueFromTableMany
                 FROM TableMany
                 GROUP BY id
               ( as T2
       ON T1.id = T2.id

How do we do this in DAX?我们如何在 DAX 中做到这一点? Using a min() function simply returns the min(value) for the entire column and is not using the relationship I've setup.使用 min() 函数只是返回整个列的 min(value) 而不是使用我设置的关系。

It's even simpler in DAX.在 DAX 中更简单。 You can create a calculated column like this:您可以像这样创建一个计算列:

minValueFromTableMany = CALCULATE(MIN(TableMany[value]),
                            ALLEXCEPT(TableOne, TableOne[id]))

This assumes that they have a relationship on the id columns.这假设它们在id列上有关系。


Here's another way to do it that should work with or without the relationship:这是另一种方法,可以在有或没有关系的情况下工作:

minValueFromTableMany = CALCULATE(MIN(TableMany[value]),
                            TableMany[id] = EARLIER(TableOne[id]))

The EARLIER function refers to the earlier row context. EARLIER函数引用较早的行上下文。


You can also use the MINX function:您还可以使用MINX函数:

minValueFromTableMany = MINX(
                            FILTER(TableMany, TableMany[id] = TableOne[id]),
                            TableMany[value])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM