Grouping Data
So far, you've learned how to use aggregates to get overall totals (and averages, and so on) for a set of rows. If you wanted to know the total dollar sales for product 14, you could execute the query we wrote earlier:
select sum(Quantity * UnitPrice * (1.0 – Discount)) as 'Total Dollar Sales' from [Order Details] where ProductID = 14
What if you were also interested in products 11, 12, and 13? You could reexecute the query several times, each time with a different product ID.
It would be better to write a single query and get a result set that looked like this:
ProductID Total Dollar Sales ----------- --------------------------------------- 11 12901.770042419434 12 12257.660041809082 13 4960.4400224685669 14 7991.4900035858154 ...
Get Sams Teach Yourself Transact-SQL in 21 Days, Second Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.