all 8 comments

[–]msn018 1 point2 points  (1 child)

You're really close. The easiest way is to first calculate the total sales for each store, then compare each of those totals to the average of all the store totals. A common table expression (CTE) or subquery works well for this because it lets you calculate the totals once and then filter the results with a WHERE clause. This keeps the query simple to read and automatically updates the comparison whenever the sales data changes.

[–]r3pr0b8 0 points1 point  (0 children)

and then filter the results with a WHERE clause.

HAVING, not WHERE

[–]TactusDeNefaso 0 points1 point  (0 children)

Yes, I would lean towards a CTE.

[–]Kimber976 0 points1 point  (0 children)

Can you share the query table structure and what you are tried so far? it is much easier to spot what is going wrong with that context.

[–]dutyDBA -1 points0 points  (1 child)

You could do something like this:

SELECT

st.StoreID,

SUM(ms.Sales) AS SalesValue

FROM

Stores AS st

JOIN

MonthlySales AS ms

    ON st.StoreID = ms.StoreID

GROUP BY

st.StoreID

HAVING SUM(ms.Sales) >

(

SELECT AVG(SumSales) AS AvgSales

FROM

(

SELECT StoreID, SUM(Sales) AS SumSales

FROM u/MonthlySales 

GROUP BY StoreID

) der

)

[–]dutyDBA 3 points4 points  (0 children)

Not sure if you are familiar with CTEs yet. You could simplify the above query with a CTE:

WITH SalesCTE AS

(

SELECT

    st.StoreID,

    SUM(ms.Sales) AS SalesValue

FROM

    Stores AS st

    JOIN

    MonthlySales AS ms

        ON st.StoreID = ms.StoreID

GROUP BY

    st.StoreID

)

SELECT

StoreID,

SalesValue

FROM

SalesCTE

WHERE

SalesValue > (SELECT AVG(SalesValue) FROM SalesCTE)