DBAtlas · Atlas de operações de banco de dados

Funções de janela (ROW_NUMBER/RANK/LAG)

Oracle

-- Rank by amount within each city and fetch the previous value:
SELECT city, name, amount,
  ROW_NUMBER() OVER (PARTITION BY city ORDER BY amount DESC) AS row_num,
  RANK()       OVER (PARTITION BY city ORDER BY amount DESC) AS rnk,
  LAG(amount)   OVER (PARTITION BY city ORDER BY created_at)      AS prev_amount
FROM sale;

O Oracle foi pioneiro nas funções analíticas (de janela); ROW_NUMBER, RANK, DENSE_RANK, LAG, LEAD, SUM/AVG OVER, NTILE e FIRST_VALUE são totalmente suportadas. Dentro de OVER, PARTITION BY define os grupos, ORDER BY a ordenação, e o frame (ROWS/RANGE BETWEEN) a janela deslizante.

PostgreSQL

-- Window functions with OVER():
SELECT city, name, amount,
  ROW_NUMBER() OVER (PARTITION BY city ORDER BY amount DESC) AS row_num,
  RANK()       OVER (PARTITION BY city ORDER BY amount DESC) AS rnk,
  LAG(amount)   OVER (PARTITION BY city ORDER BY created_at)      AS prev_amount
FROM sale;

O PostgreSQL suporta totalmente funções de janela com sintaxe SQL padrão. Estão disponíveis ROW_NUMBER/RANK/DENSE_RANK, LAG/LEAD, agregações com OVER, NTILE e FIRST_VALUE/LAST_VALUE. Definições de janela repetidas podem ser nomeadas e compartilhadas com a cláusula WINDOW.

MySQL

-- MySQL 8.0+ window functions:
SELECT city, name, amount,
  ROW_NUMBER() OVER (PARTITION BY city ORDER BY amount DESC) AS row_num,
  RANK()       OVER (PARTITION BY city ORDER BY amount DESC) AS rnk,
  LAG(amount)   OVER (PARTITION BY city ORDER BY created_at)      AS prev_amount
FROM sale;

O MySQL adicionou funções de janela na versão 8.0 (o MariaDB 10.2+ também as suporta). Estão disponíveis ROW_NUMBER, RANK, DENSE_RANK, LAG, LEAD, NTILE e agregações com OVER. Versões anteriores ao 8.0 não têm essas funções; elas eram emuladas com variáveis de usuário.

SQL Server

-- Window functions with OVER():
SELECT city, name, amount,
  ROW_NUMBER() OVER (PARTITION BY city ORDER BY amount DESC) AS row_num,
  RANK()       OVER (PARTITION BY city ORDER BY amount DESC) AS rnk,
  LAG(amount)   OVER (PARTITION BY city ORDER BY created_at)      AS prev_amount
FROM dbo.sale;

O SQL Server suporta funções de janela desde 2005 (ROW_NUMBER/RANK) e 2012 (LAG/LEAD, framing, agregações com OVER). PARTITION BY, ORDER BY e o frame ROWS/RANGE estão totalmente disponíveis. OFFSET/FETCH ou ROW_NUMBER são comuns para paginação.

MongoDB

// Window calculations with $setWindowFields:
db.sale.aggregate([
  { $setWindowFields: {
      partitionBy: "$city",
      sortBy: { amount: -1 },
      output: {
        row_num: { $documentNumber: {} },
        rnk: { $rank: {} },
        prev_amount: { $shift: { output: "$amount", by: -1 } }
      }
  } }
])

O estágio de agregação $setWindowFields, introduzido no MongoDB 5.0, fornece funções de janela: $documentNumber (ROW_NUMBER), $rank/$denseRank, $shift (LAG/LEAD), funções de agregação e janelas deslizantes (window: { documents/range }). partitionBy e sortBy correspondem a PARTITION BY/ORDER BY no SQL.

Redis

# Not applicable: there are no SQL-like window functions.

O Redis é um armazenamento chave-valor; não tem funções analíticas de janela. Para resultados ordenados, pode-se usar um Sorted Set (acesso semelhante a ranking com ZADD/ZRANGE); porém, operações de janela relacionais como PARTITION BY/LAG são feitas na camada da aplicação.

Elasticsearch

# Not applicable: there are no SQL-like window functions.
# Closest equivalent: bucket aggregations.
GET sale/_search
{ "size": 0, "aggs": { "by_city": {
  "terms": { "field": "city" },
  "aggs": { "total": { "sum": { "field": "amount" } } } } } }

O Elasticsearch não oferece funções de janela clássicas (ROW_NUMBER/RANK/LAG). Agrupamento e ordenação são feitos com o framework de agregação: uma terms aggregation se aproxima de PARTITION BY, top_hits dos registros principais, e derivative/serial_diff (pipeline aggregations) de diferenças sucessivas semelhantes a LAG.

Abrir no DBAtlas →