================================================================================
EXPERIMENT 3: OLAP OPERATIONS (PYTHON PANDAS & SQL)
Operations: Roll-up, Drill-down, Slice, Dice, Pivot
================================================================================

--------------------------------------------------------------------------------
1. PYTHON PANDAS CODE (40 Lines)
--------------------------------------------------------------------------------
import os
import pandas as pd

# ===== USER SETTINGS =====
FILE_PATH = os.path.join(os.path.dirname(__file__), "..", "datasets", "sales_olap.csv")
DIMENSIONS = ["Region", "City"]   # [Coarse, Finer]
MEASURE = "Sales"                 # Column to aggregate
SLICE_COL, SLICE_VAL = "Year", 2024
DICE_FILTERS = {"Region": ["North", "West"], "Product_Category": ["Electronics", "Home"]}
PIVOT_ROWS, PIVOT_COLS = "Region", "Product_Category"

# 1. Load dataset
df = pd.read_csv(FILE_PATH)
print(f"Loaded {df.shape[0]} rows. Columns: {list(df.columns)}")

# 2. Roll-up: Summarize up hierarchy (City -> Region)
rollup = df.groupby(DIMENSIONS[0])[MEASURE].sum().reset_index()
print("\n--- 1. ROLL-UP (Summarize by Coarser Dimension: Region) ---")
print(rollup)

# 3. Drill-down: Expand hierarchy to finer detail (Region -> City)
drilldown = df.groupby(DIMENSIONS)[MEASURE].sum().reset_index()
print("\n--- 2. DRILL-DOWN (Detailed View: Region + City) ---")
print(drilldown.head(6))

# 4. Slice: 1-Dimensional Filter
slice_df = df[df[SLICE_COL] == SLICE_VAL].groupby(DIMENSIONS[0])[MEASURE].sum().reset_index()
print(f"\n--- 3. SLICE ({SLICE_COL} == {SLICE_VAL}) ---")
print(slice_df)

# 5. Dice: Multi-Dimensional Filter (Sub-cube)
dice_mask = pd.Series(True, index=df.index)
for col, vals in DICE_FILTERS.items():
    dice_mask &= df[col].isin(vals)
dice_df = df[dice_mask].groupby(list(DICE_FILTERS.keys()))[MEASURE].sum().reset_index()
print("\n--- 4. DICE (Sub-cube Multi-Filter) ---")
print(dice_df)

# 6. Pivot: Rotate dimensions (Cross-tabulation)
pivot_df = df.pivot_table(index=PIVOT_ROWS, columns=PIVOT_COLS, values=MEASURE, aggfunc="sum", margins=True)
print("\n--- 5. PIVOT TABLE (Cross-Tabulation with Margins) ---")
print(pivot_df)

--------------------------------------------------------------------------------
2. SQL OLAP EQUIVALENTS (ROLLUP, CUBE, GROUPING SETS)
--------------------------------------------------------------------------------
-- Rollup in SQL:
SELECT region, city, SUM(sales) FROM sales GROUP BY ROLLUP(region, city);

-- Cube in SQL (All 2^N combinations):
SELECT region, category, SUM(sales) FROM sales GROUP BY CUBE(region, category);

-- Pivot in SQL using CASE WHEN:
SELECT region,
       SUM(CASE WHEN category = 'Electronics' THEN sales ELSE 0 END) AS Electronics,
       SUM(CASE WHEN category = 'Clothing'    THEN sales ELSE 0 END) AS Clothing
FROM sales GROUP BY region;
