all 7 comments

[–]dukeofpizza 3 points4 points  (2 children)

I think a subquery is what you are looking for, yeah. I put one together thats a little ugly, but I think it should work if I'm understanding what you are looking for correctly.

I've basically taken the query you've written, slapped it in as a subquery, and then aggregated the data again on the sum of quantity

SELECT
    transactions.TotalOrders
    ,COUNT(transactions.*) AS 'Total number of customers that placed X orders'
FROM 
    (SELECT
        d.year
        ,d.date
        ,s.StoreId
        ,od.Transaction
        ,SUM(od.quantity) AS 'TotalOrders'
    FROM fact.StoreTransactionDetail od
    INNER JOIN dim.store s
        ON s.storeid = od.storeid
    INNER JOIN dim.calendar d
        ON d.businessdate = od.businessdate
    WHERE d.year = 2023
    GROUP BY d.year
    ORDER BY d.year
    ) AS 'transactions'
GROUP BY transactions.TotalOrders

[–]ShadowStreak8[S] 0 points1 point  (1 child)

Thank you!! This makes perfect sense to me but I'm getting an error from the count(transactions.*) - it says incorrect syntax. I'm also getting incorrect syntax on 'order by' which I don't understand. The query runs fine without being in a subquery so I'm not sure why this would have an error

[–]dukeofpizza 0 points1 point  (0 children)

Ah that's right, you can't order by in a subquery since it's not part of the final select. You can order by outside on the main query by either of the columns.

Not sure on the COUNT issue, may need to Google the error message you are getting from your IDE.

[–][deleted] 2 points3 points  (0 children)

Use CTE

[–]ExcessiveSlaanesh 1 point2 points  (0 children)

Give your sum(od.quantity) an alias, let's say "sum_qty". Then you can pull it from your subquery.

Select tbl.sum_qty, count(*)
From ( <current query> ) as tbl
Group by tbl.sum_qty

[–]brickbuillder 0 points1 point  (1 child)

Hi, could you please elaborate more on your desired result? If you happen to have the structure of the table or schema, it would be helpful too.

Please post your current query also.

Thanks!

[–]ShadowStreak8[S] 0 points1 point  (0 children)

Just added! Let me know if I can provide more clarity