Skip to main content
cancel
Showing results for 
Search instead for 
Did you mean: 

The Power BI Data Visualization World Championships is back! It's time to submit your entry. Live now!

Reply
Anonymous
Not applicable

dax para calcular el precio de las fechas establecidas anteriores

Hola
En el modelo, hay una tabla Date,
y hay una tabla, que contiene los valores de diferentes códigos en diferentes fechas de la siguiente manera

FactValues
---------
Fecha CodeKey Valor
...
05/4/2020 ABC 11.55
...
4/15/2020 ABC 56.90
4/16/2020 ABC 45.88
4/17/2020 ABC 33.00
15/4/2020 NBV 22.99
19/4/2020 NBV 11.89
4/18/2020 ABC 43.66
...

También hay una tabla llamada tabla QuarterStart que contiene las cuatro filas siguientes y básicamente en la columna está el 05 del trimestre, es decir.

QuarterStart
------------

QuarterlyDate
05/01
05/04
05/07
05/10

Pregunta:
---------
En DAX, ¿cómo es posible tener una medida como:
a partir de hoy, todos los días, de la tabla de hechos, tome el valor del día anterior (Si cae en fin de semana, luego vaya al día anterior), luego divídalo por el valor que se asigna a la QuarterStartDate y luego -1
I.e.
valor de fecha final/valor de fecha de inicio - 1
donde [valor de fecha final] es el valor del día anterior
donde [valor de fecha de inicio] es el valor para el 5o de ese trimestre

Ejemplo:
fecha actual se dice el 17 de abril de 2020,
necesita obtener el valor de [valor de fecha final] --> 16/4/2020 que es 45.88
necesita obtener el valor de [valor de fecha de inicio] --> 05/4/2020 que es 11.55
entonces el código dax hará algo así como: medida1 a 45.88/11.55-1
Y me gustaría hacer este cálculo para cada fecha de hecho a partir de la fecha de hoy.
Si una fecha cae en fin de semana, obviamente no habrá un valor para esa fecha, así que use el valor de fecha anterior
Espero haber explicado esto correctamente...
¿Cómo es posible, por favor?

Gracias

3 REPLIES 3
Icey
Community Support
Community Support

Hola @arkiboys ,

¿Está resuelto este problema?


Si se resuelve, por favor acepte siempre las respuestas que tengan sentido como solución a su pregunta para que las personas que puedan tener la misma pregunta puedan obtener la solución directamente.


Si no, por favor hágamelo saber.


Saludos
Icey

edhans
Community Champion
Community Champion

Prueba lo de abajo. No entendía cómo entró en juego tu KeyCode, así que esto no funciona para NBV de la forma en que lo tengo porque no tenías ningún valor de inicio para NBV. Ver la parte inferior de la publicación para enlace al archivo PBIX

Measure =
VAR CurrentDate =
    MAX ( 'Fact Table'[Date] )
VAR CurrentKeyCode =
    MAX ( 'Fact Table'[KeyCode] )
VAR CurrentValue =
    MAX ( 'Fact Table'[Value] )
VAR PreviousDate =
    MAXX (
        FILTER (
            ALL ( 'Fact Table' ),
            'Fact Table'[Date] < CurrentDate
                && 'Fact Table'[KeyCode] = CurrentKeyCode
        ),
        'Fact Table'[Date]
    )
VAR PreviousValue =
    MAXX (
        FILTER (
            ALL ( 'Fact Table' ),
            'Fact Table'[Date] = PreviousDate
                && 'Fact Table'[KeyCode] = CurrentKeyCode
        ),
        'Fact Table'[Value]
    )
VAR QuarterStartDate =
    MAX ( 'Date'[Quarter Start Date] )
VAR QuarterStartValue =
    MAXX (
        FILTER (
            ALL ( 'Fact Table' ),
            'Fact Table'[Date] = QuarterStartDate
                && 'Fact Table'[KeyCode] = CurrentKeyCode
        ),
        'Fact Table'[Value]
    )
VAR Result =
    IF (
        CurrentValue <> BLANK (),
        DIVIDE ( PreviousValue, QuarterStartValue, 0 ) - 1,
        BLANK ()
    )
RETURN
    Result

Esto requiere una tabla de fechas, que está a continuación (en el código M): tenga en cuenta que la última fila del código es lo que está generando su 5o de la fecha del trimestre.

let
    Source = {Number.From(#date(2020,1,1))..Number.From(#date(2020,12,31))},
    #"Converted to Table" = Table.FromList(Source, Splitter.SplitByNothing(), {"Date"}, null, ExtraValues.Error),
    #"Changed Type" = Table.TransformColumnTypes(#"Converted to Table",{{"Date", type date}}),
    #"Inserted Year" = Table.AddColumn(#"Changed Type", "Year", each Date.Year([Date]), Int64.Type),
    #"Inserted Month" = Table.AddColumn(#"Inserted Year", "Month", each Date.Month([Date]), Int64.Type),
    #"Inserted Month Name" = Table.AddColumn(#"Inserted Month", "Month Name", each Date.MonthName([Date]), type text),
    #"Added Short Month Name" = Table.AddColumn(#"Inserted Month Name", "Short Month Name", each Text.Start([Month Name],3), type text),
    #"Added Month Year" = Table.AddColumn(#"Added Short Month Name", "Month Year", each [Short Month Name] & " " & Text.From([Year]), type text),
    #"Added Month Year Sort" = Table.AddColumn(#"Added Month Year", "Month Year Sort", each [Year]*100 + [Month], Int64.Type),
    #"Inserted Quarter Number" = Table.AddColumn(#"Added Month Year Sort", "Quarter Number", each Date.QuarterOfYear([Date]), Int64.Type),
    #"Inserted Quarter" = Table.AddColumn( #"Inserted Quarter Number","Quarter", each "Qtr " & Text.From([Quarter Number]), type text),
    #"Inserted Quarter Year Sort" = Table.AddColumn(#"Inserted Quarter", "Quarter Year Sort", each [Year] * 10 + [Quarter Number], Int64.Type),
    #"Inserted Quarter Year" = Table.AddColumn(#"Inserted Quarter Year Sort", "Quarter Year", each "Q" & Text.End([Quarter],1) & " " & Text.From([Year]), type text),
    #"Inserted Week of Year" = Table.AddColumn(#"Inserted Quarter Year", "Week of Year", each Date.WeekOfYear([Date]), Int64.Type),
    #"Inserted Week of Month" = Table.AddColumn(#"Inserted Week of Year", "Week of Month", each Date.WeekOfMonth([Date]), Int64.Type),
    #"Inserted Day" = Table.AddColumn(#"Inserted Week of Month", "Day", each Date.Day([Date]), Int64.Type),
    #"Inserted Day of Week" = Table.AddColumn(#"Inserted Day", "Day of Week", each Date.DayOfWeek([Date]), Int64.Type),
    #"Inserted Day of Year" = Table.AddColumn(#"Inserted Day of Week", "Day of Year", each Date.DayOfYear([Date]), Int64.Type),
    #"Inserted Day Name" = Table.AddColumn(#"Inserted Day of Year", "Day Name", each Date.DayOfWeekName([Date]), type text),
    #"Added IsFuture Boolean" = Table.AddColumn(#"Inserted Day Name", "IsFuture", each [Date] > DateTime.Date(DateTime.LocalNow()), type logical),
    #"Added IsInCurrentWeek" = Table.AddColumn(#"Added IsFuture Boolean", "IsInCurrentWeek", each Date.IsInCurrentWeek([Date]), type logical),
    #"Added IsInCurrentMonth" = Table.AddColumn(#"Added IsInCurrentWeek", "IsInCurrentMonth", each Date.IsInCurrentMonth([Date]), type logical),
    #"Added IsInCurrentQuarter" = Table.AddColumn(#"Added IsInCurrentMonth", "IsInCurrentQuarter", each Date.IsInCurrentQuarter([Date]), type logical),
    #"Added IsInCurrentYear" = Table.AddColumn(#"Added IsInCurrentQuarter","IsInCurrentYear", each Date.IsInCurrentYear([Date]), type logical),
    #"Added Quarter Start Date" = Table.AddColumn(#"Added IsInCurrentYear", "Quarter Start Date", each Date.AddDays(Date.StartOfQuarter([Date]), 4), type date)
in
    #"Added Quarter Start Date"

1) En Power Query, seleccione Nueva fuente y, a continuación, Consulta en blanco
2) En la cinta de opciones Inicio, seleccione el botón "Editor avanzado"
3) Retire todo lo que ve, luego pegue el código M que le he dado en esa caja.
4) Pulse Hecho
5) Consulte este artículo si necesita ayuda para usar este código M en su modelo.

La fila en rojo es la que validé para que coincida con tu ejemplo. 45.88/11.88 - 1 a 2,972020-06-12 09_58_48-Untitled - Power BI Desktop.png

PBIX está aquí.

Si necesita más ayuda, proporcione datos válidos en un formato utilizable. Cómo obtener una buena ayuda rápidamente. Ayúdanos a ayudarte.
Cómo obtener respuestas a su pregunta rápidamente
Cómo proporcionar datos de ejemplo en el foro de Power BI

Acerca de la tabla de fechas proporcionada: Creación de una tabla de fechas dinámicas en Power Query



Did I answer your question? Mark my post as a solution!
Did my answers help arrive at a solution? Give it a kudos by clicking the Thumbs Up!

DAX is for Analysis. Power Query is for Data Modeling


Proud to be a Super User!

MCSA: BI Reporting
amitchandak
Super User
Super User

@arkiboys , Probar como


Medidas ?
var _curr á maxx(allselected(Date),Date[date])
var _max á _curr-1
var _min á maxx(filter(Date, Date[QuarterlyDate]<-_max),Date[QuarterlyDate])
devolución
divide(calculate(sum(Table[Value]),filter(all(Date),Date[date] ?_max)),calculate(sum(Table[Value]),filter(all(Date),Date[date] ?_min)))-1

Share with Power BI Enthusiasts: Full Power BI Video (20 Hours) YouTube
Microsoft Fabric Series 60+ Videos YouTube
Microsoft Fabric Hindi End to End YouTube

Helpful resources

Announcements
FabCon Atlanta 2026 carousel

FabCon Atlanta 2026

Join us at FabCon Atlanta, March 16-20, for the ultimate Fabric, Power BI, AI and SQL community-led event. Save $200 with code FABCOMM.