This page is in Spanish for now — English version coming soon.
Cambio en el tiempo

Retención por cohortes

¿Cuántos clientes vuelven a comprar después de su primera compra?

Grabación en Power BI Desktop sobre el modelo Contoso-Retail, año 2024.

Los clientes agrupados por el trimestre de su primera compra y, para cada grupo, la parte que vuelve a comprar uno, dos y hasta siete trimestres después. El color va del valor más bajo al más alto de la tabla, y la fila naranja da la media de todos los grupos pesada por su tamaño. Un clic en una cohorte filtra el resto de la página por su trimestre.

Qué necesita

  • La clave de cliente y la fecha de pedido de tu tabla de ventas
  • El trimestre de tu tabla de fechas

Cómo lo conecto a mis datos

  1. Copia del archivo .dax las medidas «HTML Cohort Retention» (el visual) y «Cohort Retention Summary» (la línea de lectura).
  2. Cambia la clave de cliente y la fecha de pedido por las de tu tabla de ventas, y el trimestre por el de tu tabla de fechas.
  3. En un visual HTML Content pon la medida en Values y el trimestre en Context; activa Cross-filtering, pega la hoja de estilo del final del .dax en Stylesheet, usa «Cohort Retention Summary» como subtítulo y no filtres el año: la cohorte necesita toda la historia.

La medida completa

Es la misma que el archivo .dax de la carpeta. Cópiala con el botón.

retencion-cohortes.dax
-- The HTML: an HTML Content visual in row mode. Uses FactSales[CustomerKey], FactSales[OrderDate] and DimDate[Date], [YearQuarter] of Contoso-Retail.
-- 1. Values: the measure 'HTML Cohort Retention'. Context: 'DimDate'[YearQuarter] (one visual row each; a click on one cross-filters the page).
-- 2. Format > Cross-filtering: on. Format > Stylesheet: paste the stylesheet at the end of this file.
-- 3. Title: the visual's own title; Subtitle: the measure 'Cohort Retention Summary' (fx), the reading line.
-- By CSalcedoDataBI · https://csalcedodatabi.com/recursos/html-content-power-bi/retencion-cohortes · MIT
'HTML Cohort Retention' =
-- One visual row per cohort: the quarter of the customer's first purchase. Every row reads the whole history
-- (REMOVEFILTERS on the calendar), so its cells, the colour scale and the orange average are the same as one grid.
VAR _d = MIN ( 'DimDate'[Date] )
VAR _cur = YEAR ( _d ) * 4 + QUARTER ( _d ) - 1
VAR _first =
    CALCULATETABLE (
        ADDCOLUMNS (
            VALUES ( 'FactSales'[CustomerKey] ),
            "@fq", VAR _f = CALCULATE ( MIN ( 'FactSales'[OrderDate] ) ) RETURN YEAR ( _f ) * 4 + QUARTER ( _f ) - 1
        ),
        REMOVEFILTERS ( 'DimDate' )
    )
VAR _active =
    CALCULATETABLE (
        SELECTCOLUMNS (
            SUMMARIZE ( 'FactSales', 'FactSales'[CustomerKey], 'FactSales'[OrderDate] ),
            "k", 'FactSales'[CustomerKey],
            "q", YEAR ( 'FactSales'[OrderDate] ) * 4 + QUARTER ( 'FactSales'[OrderDate] ) - 1
        ),
        REMOVEFILTERS ( 'DimDate' )
    )
VAR _join = NATURALINNERJOIN ( SELECTCOLUMNS ( _first, "k", 'FactSales'[CustomerKey], "fq", [@fq] ), DISTINCT ( _active ) )
VAR _grid = GROUPBY ( ADDCOLUMNS ( _join, "age", [q] - [fq] ), [fq], [age], "n", COUNTX ( CURRENTGROUP (), 1 ) )
VAR _all = SUMX ( FILTER ( _grid, [age] = 0 ), [n] )
VAR _min = MAX ( 20, _all * 0.01 )
VAR _size = SELECTCOLUMNS ( FILTER ( _grid, [age] = 0 && [n] >= _min ), "c", [fq], "s", [n] )
VAR _rows = ADDCOLUMNS ( _size, "@row", RANKX ( _size, [c], , ASC ), "@lab", INT ( [c] / 4 ) & " Q" & ( MOD ( [c], 4 ) + 1 ) )
VAR _me = MAXX ( FILTER ( _rows, [c] = _cur ), [@row] )
VAR _cells =
    ADDCOLUMNS (
        FILTER ( NATURALINNERJOIN ( SELECTCOLUMNS ( _grid, "c", [fq], "age", [age], "n", [n] ), _rows ), [age] > 0 ),
        "@r", DIVIDE ( [n], [s] )
    )
VAR _maxage = MAXX ( _grid, [age] )
VAR _ages = SELECTCOLUMNS ( GENERATESERIES ( 0, _maxage ), "a", [Value] )
VAR _maxs = MAXX ( _rows, [s] )
VAR _rmin = MINX ( _cells, [@r] )
VAR _rmax = MAXX ( _cells, [@r] )
VAR _nrows = COUNTROWS ( _rows )
VAR _avg =
    ADDCOLUMNS (
        FILTER ( _ages, [a] > 0 ),
        "@avg", DIVIDE ( SUMX ( FILTER ( _cells, [age] = [a] ), [n] ), SUMX ( FILTER ( _cells, [age] = [a] ), [s] ) )
    )
VAR _mine = FILTER ( ADDCOLUMNS ( _cells, "@a", VAR _x = [age] RETURN MAXX ( FILTER ( _avg, [a] = _x ), [@avg] ) ), [c] = _cur )
VAR _lab = MAXX ( FILTER ( _rows, [c] = _cur ), [@lab] )
VAR _s = MAXX ( FILTER ( _rows, [c] = _cur ), [s] )
RETURN
    IF (
        ISBLANK ( _me ),
        BLANK (),
        "<div class=""coh-row""> "
            & CONCATENATEX (
                _ages,
                IF ( _me = 1, "<div class=""coh-colhead"" style=""grid-row:1;grid-column:" & [a] + 3 & """>" & IF ( [a] = 0, "Start", "+" & [a] & "Q" ) & "</div>" ),
                "",
                [a], ASC
            ) & " "
            & IF ( _me = 1, "<div class=""coh-colhead"" style=""grid-row:1;grid-column:1"">First buy</div><div class=""coh-colhead"" style=""grid-row:1;grid-column:2"">Customers</div>" ) & " "
            & "<div class=""coh-lab"" style=""grid-row:" & _me + 1 & ";grid-column:1"">" & _lab & "</div> "
            & "<div class=""coh-size"" style=""grid-row:" & _me + 1 & ";grid-column:2""><div class=""coh-bar"" style=""width:" & ROUND ( MAX ( 2, DIVIDE ( _s, _maxs ) * 60 ), 0 ) & "px""></div><span>" & FORMAT ( _s, "#,0", "en-US" ) & "</span></div> "
            & "<div class=""coh-cell coh-start"" style=""grid-row:" & _me + 1 & ";grid-column:3"">100%</div> "
            & CONCATENATEX (
                _mine,
                "<div class=""coh-cell" & IF ( DIVIDE ( [@r] - _rmin, _rmax - _rmin ) >= 0.55, " dark" ) & """ title=""" & _lab & " · " & [age] & " quarter(s) later: " & FORMAT ( [n], "#,0", "en-US" ) & " of " & FORMAT ( [s], "#,0", "en-US" ) & " customers bought · gap vs all groups " & FORMAT ( ( [@r] - [@a] ) * 100, "+0;-0;0", "en-US" ) & " pp"" style=""grid-row:" & _me + 1 & ";grid-column:" & [age] + 3 & ";background:rgba(45,106,159," & FORMAT ( 0.12 + 0.88 * DIVIDE ( [@r] - _rmin, _rmax - _rmin ), "0.00", "en-US" ) & ")"">" & FORMAT ( [@r], "0%", "en-US" ) & "</div>",
                "",
                [age], ASC
            ) & " "
            & IF ( _me = _nrows, "<div class=""coh-avg coh-avg-lab"" style=""grid-row:" & _nrows + 2 & ";grid-column:1 / span 2"">All groups</div><div class=""coh-avg"" style=""grid-row:" & _nrows + 2 & ";grid-column:3"">100%</div>" ) & " "
            & CONCATENATEX (
                _avg,
                IF ( _me = _nrows, "<div class=""coh-avg"" style=""grid-row:" & _nrows + 2 & ";grid-column:" & [a] + 3 & """>" & FORMAT ( [@avg], "0%", "en-US" ) & "</div>" ),
                "",
                [a], ASC
            ) & " "
            & IF ( _me = _nrows, "<div class=""coh-note"" style=""grid-row:" & _nrows + 3 & ";grid-column:1 / span " & _maxage + 3 & """>Groups of at least " & FORMAT ( _min, "#,0", "en-US" ) & " customers · darker = more of the group still buying (scale " & FORMAT ( _rmin, "0%", "en-US" ) & " to " & FORMAT ( _rmax, "0%", "en-US" ) & ") · the orange row weights every group by its size · click a group to filter the page</div>" ) & " "
            & "</div>"
    )

-- The reading line, for the visual's subtitle.
'Cohort Retention Summary' =
VAR _first =
    ADDCOLUMNS (
        VALUES ( 'FactSales'[CustomerKey] ),
        "@fq", VAR _f = CALCULATE ( MIN ( 'FactSales'[OrderDate] ) ) RETURN YEAR ( _f ) * 4 + QUARTER ( _f ) - 1
    )
VAR _active =
    SELECTCOLUMNS (
        SUMMARIZE ( 'FactSales', 'FactSales'[CustomerKey], 'FactSales'[OrderDate] ),
        "k", 'FactSales'[CustomerKey],
        "q", YEAR ( 'FactSales'[OrderDate] ) * 4 + QUARTER ( 'FactSales'[OrderDate] ) - 1
    )
VAR _join = NATURALINNERJOIN ( SELECTCOLUMNS ( _first, "k", 'FactSales'[CustomerKey], "fq", [@fq] ), DISTINCT ( _active ) )
VAR _grid = GROUPBY ( ADDCOLUMNS ( _join, "age", [q] - [fq] ), [fq], [age], "n", COUNTX ( CURRENTGROUP (), 1 ) )
VAR _all = SUMX ( FILTER ( _grid, [age] = 0 ), [n] )
VAR _min = MAX ( 20, _all * 0.01 )
VAR _rows = ADDCOLUMNS ( SELECTCOLUMNS ( FILTER ( _grid, [age] = 0 && [n] >= _min ), "c", [fq], "s", [n] ), "@lab", INT ( [c] / 4 ) & " Q" & ( MOD ( [c], 4 ) + 1 ) )
VAR _cells = ADDCOLUMNS ( FILTER ( NATURALINNERJOIN ( SELECTCOLUMNS ( _grid, "c", [fq], "age", [age], "n", [n] ), _rows ), [age] > 0 ), "@r", DIVIDE ( [n], [s] ) )
VAR _q1 = DIVIDE ( SUMX ( FILTER ( _cells, [age] = 1 ), [n] ), SUMX ( FILTER ( _cells, [age] = 1 ), [s] ) )
VAR _big = TOPN ( 1, _rows, [s], DESC )
VAR _bigc = MAXX ( _big, [c] )
VAR _last = TOPN ( 1, FILTER ( _cells, [c] = _bigc ), [age], DESC )
RETURN
    IF (
        COUNTROWS ( _rows ) > 0,
        "On average " & FORMAT ( _q1, "0%", "en-US" ) & " buy again the next quarter · the " & MAXX ( _big, [@lab] )
            & " group (" & FORMAT ( MAXX ( _big, [s] ), "#,0", "en-US" ) & " customers) still has "
            & FORMAT ( MAXX ( _last, [@r] ), "0%", "en-US" ) & " active " & MAXX ( _last, [age] ) & " quarters later"
    )


/* Stylesheet (Format > Stylesheet):
#htmlContent { font-family: 'Segoe UI', sans-serif; color: #334155; font-size: 12px; display: grid; grid-template-columns: 72px 120px; grid-auto-columns: minmax(0, 1fr); grid-template-rows: 22px; grid-auto-rows: minmax(30px, 1fr); gap: 5px; box-sizing: border-box; padding: 4px; height: 100%; overflow: hidden; }
.htmlViewerEntry, .htmlViewerEntry > div, .coh-row { display: contents; }
.htmlViewerEntry { cursor: pointer; }
.htmlViewerEntry.unselected .coh-cell, .htmlViewerEntry.unselected .coh-lab, .htmlViewerEntry.unselected .coh-size { opacity: 0.3; }
.htmlViewerEntry:hover .coh-lab { color: #E4572E; }
.htmlViewerEntry:hover .coh-cell { outline: 2px solid #1F3A5F; outline-offset: -2px; }
.coh-colhead { color: #64748B; font-size: 11px; align-self: end; text-align: center; }
.coh-lab { font-weight: 700; color: #1F3A5F; align-self: center; }
.coh-size { align-self: center; display: flex; align-items: center; gap: 6px; font-size: 11px; }
.coh-bar { height: 10px; border-radius: 5px; background: #9FB7D4; }
.coh-cell { border-radius: 6px; color: #1F3A5F; display: flex; align-items: center; justify-content: center; font-weight: 600; }
.coh-cell.dark { color: #FFFFFF; }
.coh-start { background: #1F3A5F; color: #FFFFFF; font-size: 13px; font-weight: 700; }
.coh-avg { align-self: center; text-align: center; color: #E4572E; font-weight: 700; border-top: 2px solid #E4572E; padding-top: 4px; }
.coh-avg-lab { text-align: left; }
.coh-note { font-size: 10px; color: #94A3B8; align-self: end; }
*/

El informe lee los datos de muestra por internet: al abrirlo la primera vez, pulsa Actualizar. El visual responde a los filtros de la página. Licencia MIT.

¡Contáctame!