from django.db.models import F, Window
from django.db.models.functions import RowNumber, Rank, DenseRank
from products.models import Sale
def get_sales_with_ranking():
class ShardedCounter
SHARDS = 16
SNAPSHOT_TTL = 10 # seconds
def initialize(name, redis: REDIS)
@name = name
-- ROW_NUMBER: Unique sequential number
SELECT
name,
department,
salary,
ROW_NUMBER() OVER (ORDER BY salary DESC) as overall_rank,
import pandas as pd
import plotly.express as px
df = pd.read_csv('marketing_performance.csv')
fig = px.scatter(
df,
WITH ordered_events AS (
SELECT
customer_id,
event_time,
revenue,
ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY event_time DESC) AS event_rank,
import pandas as pd
df = pd.read_parquet('events.parquet')
df['event_date'] = pd.to_datetime(df['event_date'])
df['month'] = df['event_date'].dt.to_period('M').astype(str)
import geopandas as gpd
from shapely.geometry import Point
stores = gpd.read_file('stores.geojson').to_crs(epsg=3857)
customers = gpd.GeoDataFrame(
customer_df,
CREATE TABLE daily_events (
id BIGSERIAL PRIMARY KEY,
category TEXT NOT NULL,
item_id BIGINT NOT NULL,
score NUMERIC(10,2) NOT NULL DEFAULT 0,
occurred_at TIMESTAMPTZ NOT NULL DEFAULT now()
CREATE TABLE daily_metrics (
id BIGGENERATED ALWAYS AS IDENTITY PRIMARY KEY,
tenant_id BIGINT NOT NULL,
metric TEXT NOT NULL,
day DATE NOT NULL,
count BIGINT NOT NULL DEFAULT 0,
-- Basic LATERAL join
SELECT
u.username,
recent.order_id,
recent.total,
recent.created_at
class ReportsController < ApplicationController
def monthly_sales
year = params.fetch(:year, Date.current.year).to_i
rows = Order.monthly_sales(year: year)
@report = MonthlySalesReport.new(rows, year: year)
-- ROLLUP for hierarchical subtotals
SELECT
COALESCE(category, 'ALL CATEGORIES') AS category,
COALESCE(subcategory, 'ALL SUBCATEGORIES') AS subcategory,
SUM(revenue) AS total_revenue,
COUNT(*) AS order_count