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

The Power BI Data Visualization World Championships is back! Get ahead of the game and start preparing now! Learn more

Reply
metricwise
Regular Visitor

Cree dos columnas juntas para el caso de uso MTD/YTD

Hola

Estoy tratando de crear dos columnas - "Fechas", "Etiqueta" de tal manera que "Fechas" contiene todas las fechas que caen en MTD y luego las filas correspondientes a que deben etiquetarse como "MTD".

Intenté usar Table.FromList sin embargo no sé cómo agregar crear dos columnas.

Cuando uso Table.FromRecords, obtengo este error - "No podemos convertir el valor #date(2020, 8, 1) al tipo Record"

"Crear tabla" - Table.FromList(List.Dates(MonthStart, Duration.Days(Yesterday - MonthStart) + 1, #duration(1, 0, 0, 0)), Splitter.SplitByNothing(), "Dates" )

Por favor, sugiera una solución.

let
    Source = Table.FromRows(Json.Document(Binary.Decompress(Binary.FromText("i44FAA==", BinaryEncoding.Base64), Compression.Deflate)), let _t = ((type nullable text) meta [Serialized.Text = true]) in type table [Column1 = _t]),
    #"Changed Type" = Table.TransformColumnTypes(Source,{{"Column1", type text}}),

    Today = DateTime.Date(DateTime.FixedLocalNow()),
    YearStart = Date.Day(#datetime(Date.Year(Today), 1, 1)),
    QuarterStart = Date.StartOfQuarter(Today),
    MonthStart = Date.StartOfMonth(Today),
    WeekStart = Date.StartOfWeek(Today, Day.Monday),
    Yesterday = Date.AddDays(Today, -1),

    #"Create Table" = Table.FromRecords(List.Dates(MonthStart, Duration.Days(Yesterday - MonthStart) + 1, #duration(1, 0, 0, 0))),
in
    #"Create Table"

1 ACCEPTED SOLUTION
Anonymous
Not applicable

Hola @metricwise ,

Puede agregar una columna personalizada usando así:

8.20 case5 follow.PNGEl código completo en Advanced Editor:

let
    Source = Table.FromRows(Json.Document(Binary.Decompress(Binary.FromText("VdDLCcAwDAPQXXIuyHL+s4Tsv0ZTSrF6fMgG2WulDsLNLe1rpQEPNGRNiqIGKpomPVAwNJmBDFqIoHRwUEpM8GnB+U4aWIRnswYH2EIN7DIKjtA5euoFbtrN/x9xberfT/YN", BinaryEncoding.Base64), Compression.Deflate)), let _t = ((type nullable text) meta [Serialized.Text = true]) in type table [Value = _t]),
    #"Changed Type" = Table.TransformColumnTypes(Source,{{"Value", type date}}),
    #"Added Custom1" = Table.AddColumn(#"Changed Type", "QTD", each if Date.IsInCurrentQuarter([Value]) then "QTD" else null),
    #"Added Custom2" = Table.AddColumn(#"Added Custom1", "YTD", each if Date.IsInCurrentYear([Value]) then "YTD" else null),
    #"Added Custom" = Table.AddColumn(#"Added Custom2", "MTD", each if Date.IsInCurrentMonth([Value]) then "MTD" else null),
    #"Sorted Rows" = Table.Sort(#"Added Custom",{{"Value", Order.Descending}}),
    #"Reordered Columns" = Table.ReorderColumns(#"Sorted Rows",{"Value", "MTD", "QTD", "YTD"})
in
    #"Reordered Columns"

Entonces la tabla final se verá así:

8.20 case5 follow2.PNG

Saludos

Eyelyn Qin

View solution in original post

6 REPLIES 6
Anonymous
Not applicable

Hola @metricwise ,

¿He respondido a tu pregunta? Por favor, marque mi respuesta como solución, gracias.

Anonymous
Not applicable

Hola @metricwise ,

Según mi opinión, desea crear la columna Fecha con una columna Etiqueta para especificar el MTD/QTD/YTD ,¿verdad?

Puede usar la siguiente fórmula:

DateTable =
CALENDAR ( "2019/11/1", TODAY () )
latestDateColumn =
CALCULATE ( MAX ( DateTable[Date] ), ALL ( DateTable ) )
monthDiff =
IF (
    DATEDIFF (
        SELECTEDVALUE ( DateTable[Date] ),
        SELECTEDVALUE ( DateTable[latestDateColumn] ),
        MONTH
    ) = 0,
    "MTD"
)
quarterDiff =
IF (
    DATEDIFF (
        SELECTEDVALUE ( DateTable[Date] ),
        SELECTEDVALUE ( DateTable[latestDateColumn] ),
        QUARTER
    ) = 0,
    "QTD"
)
yearDiff =
IF (
    DATEDIFF (
        SELECTEDVALUE ( DateTable[Date] ),
        SELECTEDVALUE ( DateTable[latestDateColumn] ),
        YEAR
    ) = 0,
    "YTD"
)
Tag =
IF (
    DATEDIFF (
        SELECTEDVALUE ( DateTable[Date] ),
        SELECTEDVALUE ( DateTable[latestDateColumn] ),
        MONTH
    ) = 0,
    "MTD",
    IF (
        DATEDIFF (
            SELECTEDVALUE ( DateTable[Date] ),
            SELECTEDVALUE ( DateTable[latestDateColumn] ),
            QUARTER
        ) = 0,
        "QTD",
        IF (
            DATEDIFF (
                SELECTEDVALUE ( DateTable[Date] ),
                SELECTEDVALUE ( DateTable[latestDateColumn] ),
                YEAR
            ) = 0,
            "YTD"
        )
    )
)

Mi visualización tiene este aspecto:

8.20.5.2.PNG

¿Es el resultado lo que quieres? Si tiene alguna pregunta, cargue algunas muestras de datos y la salida esperada.

Por favor, enmascarar los datos confidenciales antes de cargar.

Saludos

Eyelyn Qin

hola @Eyelyn9 ,

Gracias por su respuesta. Veo que ha escrito una consulta DAX para esto sin embargo quiero implementarlo en M para una ejecución más rápida.

Anonymous
Not applicable

Hola @metricwise ,

Puede agregar una columna personalizada usando así:

8.20 case5 follow.PNGEl código completo en Advanced Editor:

let
    Source = Table.FromRows(Json.Document(Binary.Decompress(Binary.FromText("VdDLCcAwDAPQXXIuyHL+s4Tsv0ZTSrF6fMgG2WulDsLNLe1rpQEPNGRNiqIGKpomPVAwNJmBDFqIoHRwUEpM8GnB+U4aWIRnswYH2EIN7DIKjtA5euoFbtrN/x9xberfT/YN", BinaryEncoding.Base64), Compression.Deflate)), let _t = ((type nullable text) meta [Serialized.Text = true]) in type table [Value = _t]),
    #"Changed Type" = Table.TransformColumnTypes(Source,{{"Value", type date}}),
    #"Added Custom1" = Table.AddColumn(#"Changed Type", "QTD", each if Date.IsInCurrentQuarter([Value]) then "QTD" else null),
    #"Added Custom2" = Table.AddColumn(#"Added Custom1", "YTD", each if Date.IsInCurrentYear([Value]) then "YTD" else null),
    #"Added Custom" = Table.AddColumn(#"Added Custom2", "MTD", each if Date.IsInCurrentMonth([Value]) then "MTD" else null),
    #"Sorted Rows" = Table.Sort(#"Added Custom",{{"Value", Order.Descending}}),
    #"Reordered Columns" = Table.ReorderColumns(#"Sorted Rows",{"Value", "MTD", "QTD", "YTD"})
in
    #"Reordered Columns"

Entonces la tabla final se verá así:

8.20 case5 follow2.PNG

Saludos

Eyelyn Qin

Ajinkya369
Resolver III
Resolver III

Hola @metricwise ,

Hice algún cambio en su código m para resolver el error que está recibiendo.

Reemplaqué la función Table.FromRecord por Table.FromValue

Aquí está la salida de su código M:

answer.JPG

Código M modificado:

let
    Source = Table.FromRows(Json.Document(Binary.Decompress(Binary.FromText("i44FAA==", BinaryEncoding.Base64), Compression.Deflate)), let _t = ((type nullable text) meta [Serialized.Text = true]) in type table [Column1 = _t]),
    #"Changed Type" = Table.TransformColumnTypes(Source,{{"Column1", type text}}),

    Today = DateTime.Date(DateTime.FixedLocalNow()),
    YearStart = Date.Day(#datetime(Date.Year(Today), 1, 1)),
    QuarterStart = Date.StartOfQuarter(Today),
    MonthStart = Date.StartOfMonth(Today),
    WeekStart = Date.StartOfWeek(Today, Day.Monday),
    Yesterday = Date.AddDays(Today, -1),

    #"Create Table" = Table.FromValue(List.Dates(MonthStart, Duration.Days(Yesterday - MonthStart) + 1, #duration(1, 0, 0, 0)))
in
    #"Create Table"

Si su problema se resuelve, acepte esta respuesta como solución.

Gracias

Ajinkya

Análisis de datos maestros -

amitchandak
Super User
Super User

@metricwise, hay código aquí para generar un calendario usando M.

ver si eso puede ayudar

https://radacad.com/create-a-date-dimension-in-power-bi-in-4-steps-step-1-calendar-columns

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
November Power BI Update Carousel

Power BI Monthly Update - November 2025

Check out the November 2025 Power BI update to learn about new features.

Fabric Data Days Carousel

Fabric Data Days

Advance your Data & AI career with 50 days of live learning, contests, hands-on challenges, study groups & certifications and more!

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.

Top Kudoed Authors