T-SQL reference › GROUP BY

GROUP BY in SQL Server: one row per bucket

GROUP BY collapses rows that share a value into one. COUNT and SUM then talk about that pile. Any column you SELECT without totalling must appear in the GROUP BY.

By status

SELECT status,
       COUNT(*) AS orders,
       SUM(total_amount) AS revenue
FROM Orders
GROUP BY status
ORDER BY revenue DESC;

If you add customer_id to the SELECT, you must add it to the GROUP BY, or SQL Server raises Msg 8120.

Try it on Harbour & Co

Tom Gallagher (Warehouse Lead) needs this now: “For the ops meeting: how many orders and how much revenue in each status?” Write the query, run it, send the results. On the paid plan.

Take the ticket →

Learn it on a real ticket

Monday is free on WorkSQL. A colleague’s ticket lands, you write the T-SQL, we mark it. No videos. Five minutes.

Clock in free See Monday’s tickets