Skip to content

Instantly share code, notes, and snippets.

@atapatel
Created May 25, 2021 11:48
Show Gist options
  • Save atapatel/36b8b3339b622cf8cedb9c7b709abcf5 to your computer and use it in GitHub Desktop.
Save atapatel/36b8b3339b622cf8cedb9c7b709abcf5 to your computer and use it in GitHub Desktop.
demo query
select *, (select sum(o2.tax_total) from orders o2 where find_in_set(o2.order_id,x.order_ids) ) from (
SELECT
t.name,
sum(oi.qty * oi.origin_price) as gross_sales,
count(DISTINCT o.order_id) as total_orders,
(sum(oi.qty * oi.origin_price) / count(DISTINCT o.order_id)) as aov,
sum((oi.origin_price - oi.checkout_price) * oi.qty) as discounts,
sum(oi.qty * if(av.variant_id is null or av.price_type = 2, 1, 0)) as sold_units,
sum(oi.qty * if(av.variant_id is not null and av.price_type = 1, if(av.variant_type = 1, av.variant_qty, av.variant_qty * 3.5), 0)) as sold_grams,
av.variant_type,
sum(p.wholesale_price * oi.qty) as cogs,
sum(oi.checkout_price * oi.qty) as net_sales,
group_concat(distinct o.order_id) as order_ids
FROM
orders o
JOIN drops d ON d.order_id = o.order_id
JOIN order_items oi ON o.order_id = oi.order_id
JOIN products p ON oi.product_id = p.product_id
JOIN attribute_variants av ON p.variant_id = av.variant_id
JOIN territories t ON t.territory_id = d.territory_id
WHERE
o.disp_id = 1 AND
o.is_deleted = 0 AND
d.delivery_status NOT IN(5, 6)
GROUP BY d.territory_id
) as x
ORDER BY x.net_sales DESC
@atapatel
Copy link
Author

SELECT x.name ,
x.tax_total,
sum(oi.qty * oi.origin_price) as gross_sales,
count(DISTINCT x.order_id) as total_orders,
(sum(oi.qty * oi.origin_price) / count(DISTINCT x.order_id)) as aov,
sum((oi.origin_price - oi.checkout_price) * oi.qty) as discounts,
sum(oi.qty * if(av.variant_id is null or av.price_type = 2, 1, 0)) as sold_units,
sum(oi.qty * if(av.variant_id is not null and av.price_type = 1, if(av.variant_type = 1, av.variant_qty, av.variant_qty * 3.5), 0)) as sold_grams,
av.variant_type,
sum(p.wholesale_price * oi.qty) as cogs,
sum(oi.checkout_price * oi.qty) as net_sales
(SELECT
t.territory_id,
x.order_id as order_id,
t.name as name,
sum(o.tax_total) tax_total
FROM
orders o
JOIN drops d ON d.order_id = o.order_id
JOIN territories t ON t.territory_id = d.territory_id
WHERE
o.disp_id = 1 AND
o.is_deleted = 0 AND
d.delivery_status NOT IN(5, 6)
GROUP BY d.territory_id, o.order_id
) as x

JOIN order_items oi ON x.order_id = oi.order_id 
JOIN products p ON oi.product_id = p.product_id 
JOIN attribute_variants av ON p.variant_id = av.variant_id

group by x.territory_id

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment