Cumulative sum on different columns grouped by date and filtered differently

点点圈 提交于 2021-01-29 02:35:46

问题


I would like to create three cumulative sum columns based on three different column. Each cumulative sum must be calculated as follows:

  • should be grouped by the same date in the dte column
  • column A should be filtered ASC before cumulative sum operation is done
  • column B & C should be filtered DESC before cumulative sum operation.

Should I create new tables with columns A, B, C separated from each other?

+-----------+----+----------+---+----+-----+----------+----------+----------+
|    dte    | id | last_dte | a | b  |  c  | a_cumsum | b_cumsum | c_cumsum |
+-----------+----+----------+---+----+-----+----------+----------+----------+
| 12/4/2018 |  1 | 3-Dec    | 2 |  8 | 200 |        2 |          |          |
| 12/4/2018 |  2 | 3-Dec    | 2 |  5 | 150 |        4 |          |          |
| 12/4/2018 |  8 | 3-Dec    | 2 | 25 |  88 |        6 |          |          |
| 12/4/2018 |  9 | 3-Dec    | 2 | 89 | 456 |        8 |          |          |
| 12/3/2018 | 12 | 2-Dec    | 2 |  1 | 124 |        2 |          |          |
| 12/3/2018 | 13 | 2-Dec    | 2 |  5 |  46 |        4 |          |          |
| 12/3/2018 | 19 | 2-Dec    | 2 | 22 |  10 |        6 |          |          |
+-----------+----+----------+---+----+-----+----------+----------+----------+

回答1:


This is a classic example of a Cumulative Sum DAX Pattern.

You do not need separate tables.

As a calculated column

a_cum = 
VAR CurrentID = [id]
RETURN
    CALCULATE (
        SUM ( Table01[a] ),
        FILTER (
            ALLEXCEPT ( Table01, Table01[dte] ),
            Table01[id] <= CurrentID
        )
    )

The b_cum and c_cum columns are analogous. Just switch out the column you're referencing and change the direction of the inequality for DESC instead of ASC. For example,

b_cum = 
VAR CurrentID = [id]
RETURN
    CALCULATE (
        SUM ( Table01[b] ),
        FILTER (
            ALLEXCEPT ( Table01, Table01[dte] ),
            Table01[id] >= CurrentID
        )
    )

This should give you a table like this:


Note that these are ordering the cumulative sum by the id column (ASC for a_cum and descending for b_cum and c_cum). If you need to sort by the values of the columns rather than their id, then I'd suggest adding a calculated column for each to rank them how you want. Then use the rank column instead of the id column in your DAX.



来源:https://stackoverflow.com/questions/53621328/cumulative-sum-on-different-columns-grouped-by-date-and-filtered-differently

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!