Skip to content
Advertisement

Combine ORDER BY and GROUP BY and a counter

I use this SQL query to get customer order lines from an imported CSV file

and get this result

Now I would like to produce 2 different results, where one, in addition to order by ordernr also group them by their customerid

and another where I get a counter (the cnt column) with how many times a customer/customerid occurs


I’ve tried several join and group by solutions, though my SQL skills aren’t good enough to get me these results.

Advertisement

Answer

You can just order by customer prior to ordernr to group the values, and use COUNT as a window function to get the count of each customerid. Combining both in one query (and considering your initial query as a view):

Output (based on the results of your original query):

Demo on SQLFiddle

Update

Based on discussion in comments, the ordering actually needs to be done so that all a customers orders are grouped together and sorted into the list based on the minimum order number for that customer. This can be done with this query:

Output (for the expanded demo):

Demo on SQLFiddle

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement