Repository navigation
custom SQL QUERY: FINDING TOTAL SALES FOR DISTINCT BRAND AS ATTACHED IN THE XLS #40964
Replies: 2 comments
|
Hi @partha-smsrc! I'm Dosu and I'm helping the Apache Superset team. This is a common question — in fact, an almost identical one was asked previously [1]. Here's the situation: The core challenge: Superset's custom SQL metric field accepts aggregate expressions (like What won't work:
Recommended approach — Virtual Dataset: The most reliable solution is to create a virtual (SQL) dataset in SQL Lab, then build your chart on top of it: SELECT Brand, SUM(Sales) AS Total_Sales
FROM your_table
GROUP BY BrandThis gives you one row per distinct brand with its total sales. You can then use a Table chart with subtotals enabled to get the grand total, or add a simple Alternative — Use dimensions in the chart: If you add Both approaches avoid needing to hardcode any brand names and work dynamically regardless of how many brands appear multiple times in your data. To reply, just mention @dosu. Docs are dead. Just use Dosu. |
|
The reason standard Because Superset chart-level custom SQL metrics are injected directly into the Here are the two ways to solve this in Superset: Method 1: Pre-aggregate in a Virtual Dataset (Recommended)The cleanest approach in Superset is to create a lightweight virtual dataset:
SELECT
Brand,
MAX(Sales) AS brand_sales
FROM your_original_table
GROUP BY Brand
SUM(brand_sales)When Metformin appears multiple times, Method 2: Analytical Window Function (if supported by your SQL Dialect)If your underlying database (PostgreSQL, Trino, Snowflake, Databricks, ClickHouse) supports window functions inside custom expressions, you can create a Calculated Column on your dataset: CASE
WHEN ROW_NUMBER() OVER (PARTITION BY Brand ORDER BY Sales DESC) = 1 THEN Sales
ELSE 0
ENDName this calculated column SUM(distinct_brand_sales)This sets duplicate rows for any brand to 0 while preserving the primary sales entry, producing the expected 200 total cleanly. |
Uh oh!
There was an error while loading. Please reload this page.
I have a dataset containing two columns: Brand and Sales. One of the brands, Metformin, appears multiple times, and some sales values (such as 50 and 30) are also repeated.
I want to create a Total column that calculates the sum of sales considering only distinct brands. For example, given sales values of 40, 50, 50, 30, and 30, the total should be 200. However, since Metformin appears more than once, it should only be counted once when calculating this total.
Additionally, I will be writing this logic using custom SQL at the chart level, not directly on the database, so I cannot use a full query structure like SELECT * FROM ....
Dataset (1).xlsx
@dosu
All reactions