6

I have a SQL statement like this:

(ROW_NUMBER() OVER (PARTITION BY a.[market], [MEASURE_TYPE] 
                    ORDER BY AM, REP, ORDER_KEY)) AS ORDER_KEY

I want to write a DAX to implement the above SQL statement.

James Z
  • 12,209
  • 10
  • 24
  • 44
Yousuf Sultan
  • 3,055
  • 8
  • 35
  • 63

2 Answers2

3

This is not as simple in DAX as in SQL. Here is an example:

Order Key Within Partition = 
VAR CurrentMarket = [Market]
VAR CurrentMeasureType = [MeasureType]
VAR CurrentAM = [AM]
VAR CurrentREP = [REP]
VAR CurrentOrderKey = [OrderKey]

VAR CurrentPartition = FILTER (
    a, -- the table name
    [Market] = CurrentMarket
    && [MeasureType] = CurrentMeasureType
)

RETURN SUMX (
    CurrentPartition,
    IF (
        ISONORAFTER (
            CurrentAM, [AM], ASC,
            CurrentREP, [REP], ASC,
            CurrentOrderKey, [OrderKey], ASC
        ),
        1
    )
)

Result

EDIT: Power Query would be better to achieve this.

let
    /* Steps so far */
    Source = ...,
    ...
    a = ...,
    /* End of steps so far */

    /* Add steps below to add Order Key Within Partition column */
    Partitions = Table.Group(
        a,
        {"Market", "MeasureType"}, {"Partition", each _}
    )[Partition],
    AddedOrderKeys = List.Transform(
        Partitions,
        each Table.AddIndexColumn(
            Table.Sort(_, {"AM", "REP", "OrderKey"}),
            "Order Key Within Partition",
            1
        )
    ),
    Result = Table.Combine(AddedOrderKeys)
in
    Result
Kosuke Sakai
  • 2,336
  • 2
  • 5
  • 12
  • I tried to implement this, but after writing the code for new column, the screen is stuck in working on it for the last four hours. My table has almost 3 million records. – Yousuf Sultan Jan 07 '20 at 12:46
  • 1
    Too bad! Power Query based approach would be better in that case. I will update the answer. – Kosuke Sakai Jan 07 '20 at 13:41
  • The power query approach is great, elegant and fast! Thank you so much! Kudos to @Kosuke Sakai! – Simon Jul 01 '20 at 18:25
1

I contribute with an alternative solution to the RANKX. The answer containing the Power Query is the correct one because avoid using calculated columns.

Sales[Sequence by Customer] = 

VAR CurrentDate = Sales[Date]

VAR CurrentTime = Sales[Time]

RETURN COUNTROWS (

    FILTER (

        CALCULATETABLE (

            Sales, 

            ALLEXCEPT ( Sales, Sales[Customer] )

        ),

        Sales[Date] < CurrentDate

          || ( Sales[Date] = CurrentDate 

               && Sales[Time] <= CurrentTime )

    )

)

Source

Seymour
  • 3,104
  • 2
  • 22
  • 46