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

Register now to learn Fabric in free live sessions led by the best Microsoft experts. From Apr 16 to May 9, in English and Spanish.

Reply
Andrew17
Helper I
Helper I

Convertir fechas que abarcan varios meses en varios registros

Hola

Tengo algunos datos que muestran la fecha de inicio y finalización de un proceso, pero me preguntaba si había una manera de dividir estas fechas en intervalos mensuales. Para poder conseguir una línea por cada mes.

Al igual que con los datos de muestra a continuación:

ID únicoFecha de inicioFecha de finalización
AA2020-05-052020-06-05
Desactivado2020-04-032020-06-19

Ca

2020-05-15

2020-05-25

Se convertiría en:

ID únicoFecha de inicioFecha de finalización
AA2020-05-052020-05-31
AA2020-06-012020-06-05
Desactivado2020-04-032020-04-30
Desactivado2020-05-012020-05-31
Desactivado2020-06-012020-06-19
Ca2020-05-152020-05-25

Me preguntaba si hay una facilidad para hacer esto en Power Query o DAX? Quiero tratar de evitar hacer esto en Excel o VBA.

1 ACCEPTED SOLUTION

Gracias, @ImkeF por resaltarlo, de hecho, he aprendido mucho de ti.
De alguna manera me perdí verificarlo a fondo.

He creado esta función para traer el intervalo de fechas y funciona bien. De hecho, https://excelfort.com/allocate-amount-monthly-excel-powerquery/ he https://excelfort.com/allocate-amount-monthly-excel-powerquery/

let
    Source = (pStart as date, pEnd as date) =>
let

Source = List.Generate(
                ()=> [fDate = pStart, fDay= if Date.EndOfMonth(fDate) < pEnd then Date.EndOfMonth(fDate) else pEnd ],      
                each [fDate] <= pEnd,
                each 
                let EoM = Date.EndOfMonth( Date.AddMonths([fDate],1)) in 
                [fDate= Date.AddDays(Date.EndOfMonth([fDate]),1) , fDay= if EoM > pEnd then pEnd else Date.EndOfMonth(fDate)]       
        ),
        #"Converted to Table" = Table.FromList(Source, Splitter.SplitByNothing(), null, null, ExtraValues.Error),
        #"Expanded Column1" = Table.ExpandRecordColumn(#"Converted to Table", "Column1", {"fDate", "fDay"}, {"fDate", "fDay"}),
        #"Changed Type" = Table.TransformColumnTypes(#"Expanded Column1",{{"fDate", type date}, {"fDay", type date}}),
        #"Renamed Columns" = Table.RenameColumns(#"Changed Type",{{"fDate", "Date Start"}, {"fDay", "Date End"}})
    in
        #"Renamed Columns"
in

Source


Gracias de nuevo

Did I answer your question? Mark my post as a solution! and hit thumbs up


Subscribe and learn Power BI from these videos

Website LinkedIn PBI User Group

View solution in original post

4 REPLIES 4
Fowmy
Super User
Super User

@Andrew17

Por favor, encuentre adjunto el archivo que divide la fecha en rangos según lo requiera.

Puede descargar el archivo: HERE


He creado una función para proporcionar la fecha de inicio y finalización, a continuación, le dará el rango en el medio, entonces se trata de expandirse en filas.
Más sobre la división de fechas en mi blog: https://excelfort.com/allocate-amount-monthly-excel-powerquery/

let
    Source = (pStart as date, pEnd as date) =>
let

Source = List.Generate(
                ()=> [fDate = pStart, fDay= if Date.EndOfMonth(fDate) < pEnd then Date.EndOfMonth(fDate) else pEnd ],      
                each [fDate] <= pEnd,
                each 
                let EoM = Date.EndOfMonth( Date.AddMonths([fDate],1)) in 
                [fDate= Date.AddDays(Date.EndOfMonth([fDate]),1) , fDay= if EoM > pEnd then pEnd else Date.EndOfMonth(fDate)]       
        ),
        #"Converted to Table" = Table.FromList(Source, Splitter.SplitByNothing(), null, null, ExtraValues.Error),
        #"Expanded Column1" = Table.ExpandRecordColumn(#"Converted to Table", "Column1", {"fDate", "fDay"}, {"fDate", "fDay"}),
        #"Changed Type" = Table.TransformColumnTypes(#"Expanded Column1",{{"fDate", type date}, {"fDay", type date}}),
        #"Renamed Columns" = Table.RenameColumns(#"Changed Type",{{"fDate", "Date Start"}, {"fDay", "Date End"}})
    in
        #"Renamed Columns"
in

Source




Fowmy_0-1596091646824.png

________________________

¿He respondido a tu pregunta? Marque este post como una solución, esto ayudará a otros!.

Haga clic en el icono Thumbs-Up a la derecha si le gusta esta respuesta 🙂

YoutubeLinkedin

Did I answer your question? Mark my post as a solution! and hit thumbs up


Subscribe and learn Power BI from these videos

Website LinkedIn PBI User Group

Hola @Fowmy

no parece que sus resultados sean iguales a la solicitud.

Para @Andrew17 ,

He creado una función hace algún tiempo que crea este tipo de intervalos: https://www.thebiccountant.com/2017/12/11/date-datesbetween-retrieve-dates-between-2-dates-power-bi-...

Solo devolveré la fecha de finalización de cada mes (u otro intervalo que necesite).

Pero las otras columnas se pueden resolver con bastante facilidad:

let
    Source = Table.FromRows(Json.Document(Binary.Decompress(Binary.FromText("i45WcnRU0lEyMjAy0DUwBSI4xwzEidUBKnCCi5noGhgjKTC0hChwRjLB0BSJYwQ0IRYA", BinaryEncoding.Base64), Compression.Deflate)), let _t = ((type nullable text) meta [Serialized.Text = true]) in type table [#"Unique ID" = _t, #"Start Date" = _t, #"End Date " = _t]),
    #"Changed Type" = Table.TransformColumnTypes(Source,{{"Unique ID", type text}, {"Start Date", type date}, {"End Date ", type date}}),
    #"Invoked Custom Function" = Table.AddColumn(#"Changed Type", "fnDatesBetwen", each fnDatesBetwen([Start Date], [#"End Date "], "Month")),
    #"Expanded fnDatesBetwen" = Table.ExpandListColumn(#"Invoked Custom Function", "fnDatesBetwen"),
    AddStartOfMonth = Table.AddColumn(#"Expanded fnDatesBetwen", "StartOfMonth", each Date.StartOfMonth([fnDatesBetwen])),
    #"Inserted Latest" = Table.AddColumn(AddStartOfMonth, "Start", each List.Max({[StartOfMonth], [Start Date]}), type date),
    #"Inserted Earliest" = Table.AddColumn(#"Inserted Latest", "End", each List.Min({[#"End Date "], [fnDatesBetwen]}), type date),
    Cleanup = Table.SelectColumns(#"Inserted Earliest",{"Unique ID", "Start", "End"})
in
    Cleanup

También encontrará el archivo adjunto.

Imke Feldmann (The BIccountant)

If you liked my solution, please give it a thumbs up. And if I did answer your question, please mark this post as a solution. Thanks!

How to integrate M-code into your solution -- How to get your questions answered quickly -- How to provide sample data -- Check out more PBI- learning resources here -- Performance Tipps for M-queries

Gracias, @ImkeF por resaltarlo, de hecho, he aprendido mucho de ti.
De alguna manera me perdí verificarlo a fondo.

He creado esta función para traer el intervalo de fechas y funciona bien. De hecho, https://excelfort.com/allocate-amount-monthly-excel-powerquery/ he https://excelfort.com/allocate-amount-monthly-excel-powerquery/

let
    Source = (pStart as date, pEnd as date) =>
let

Source = List.Generate(
                ()=> [fDate = pStart, fDay= if Date.EndOfMonth(fDate) < pEnd then Date.EndOfMonth(fDate) else pEnd ],      
                each [fDate] <= pEnd,
                each 
                let EoM = Date.EndOfMonth( Date.AddMonths([fDate],1)) in 
                [fDate= Date.AddDays(Date.EndOfMonth([fDate]),1) , fDay= if EoM > pEnd then pEnd else Date.EndOfMonth(fDate)]       
        ),
        #"Converted to Table" = Table.FromList(Source, Splitter.SplitByNothing(), null, null, ExtraValues.Error),
        #"Expanded Column1" = Table.ExpandRecordColumn(#"Converted to Table", "Column1", {"fDate", "fDay"}, {"fDate", "fDay"}),
        #"Changed Type" = Table.TransformColumnTypes(#"Expanded Column1",{{"fDate", type date}, {"fDay", type date}}),
        #"Renamed Columns" = Table.RenameColumns(#"Changed Type",{{"fDate", "Date Start"}, {"fDay", "Date End"}})
    in
        #"Renamed Columns"
in

Source


Gracias de nuevo

Did I answer your question? Mark my post as a solution! and hit thumbs up


Subscribe and learn Power BI from these videos

Website LinkedIn PBI User Group

Greg_Deckler
Super User
Super User

@Andrew17 - Claro, puede GENERATESERIES y UNION para hacerlo en DAX. Estoy seguro de que hay una manera de hacerlo en Power Query demasiado @ImkeF .


@ me in replies or I'll lose your thread!!!
Instead of a Kudo, please vote for this idea
Become an expert!: Enterprise DNA
External Tools: MSHGQM
YouTube Channel!: Microsoft Hates Greg
Latest book!:
The Definitive Guide to Power Query (M)

DAX is easy, CALCULATE makes DAX hard...

Helpful resources

Announcements
Microsoft Fabric Learn Together

Microsoft Fabric Learn Together

Covering the world! 9:00-10:30 AM Sydney, 4:00-5:30 PM CET (Paris/Berlin), 7:00-8:30 PM Mexico City

PBI_APRIL_CAROUSEL1

Power BI Monthly Update - April 2024

Check out the April 2024 Power BI update to learn about new features.

April Fabric Community Update

Fabric Community Update - April 2024

Find out what's new and trending in the Fabric Community.