laika222
4/6/2017 - 3:47 PM

Line 2 shows how to GROUP BY Last Name, and then ORDER BY two things - first, the COUNT(OrderID), and then the LastName, ordering in ASC ord

Line 2 shows how to GROUP BY Last Name, and then ORDER BY two things - first, the COUNT(OrderID), and then the LastName, ordering in ASC order

-- GROUPs rows by playerID (multiple playerID rows will be collapsed into one). The non-GROUP BY columns (the columns other than playerID) must be aggregate columns (SUM, AVG, COUNT, etc.) - in other words, since it'll be collapsing multiple values for that playerID into a single space, you need to tell it how to collapse the values. SQL Server will give you an error if the non-GROUP BY columns are not aggregate, and MySQL will let you proceed, but it will simply choose the first value column for each grouping, so you'll be getting incomplete data. 
SELECT playerID, COUNT(yearID) AS 'Years Played', SUM(HR) AS 'Home Runs' FROM Batting 
GROUP BY playerID ORDER BY SUM(HR) DESC

-- You can add a calculation column while GROUPing (see 'RBIs Times 2') as long as the basis of the calculation is an aggregate (for example, you can't calculate (RBI * 2) and then GROUP, you must calculate based on an aggregate like (SUM(RBI) * 2). If you base the calculation on something that's not aggregate like (RBI * 2), SQL Server will give you an error, and MySQL will pick the first value in the column for that grouping, resulting in a calculation that will likely be very off.) Note that MySQL will not let you GROUP or ORDER by a column alias (the AS part) as seen below, but SQL Server will let you do this.
SELECT playerID, COUNT(yearID) AS 'Years Played', SUM(HR) 'Home Runs', (SUM(RBI) * 2) AS 'RBIs Times 2' from Batting
GROUP BY playerID 
ORDER BY 'RBIs Times 2' DESC

-- You can GROUP without an aggregate as long as you GROUP BY each non-aggregate column in some order (is this useful at all?)
select customer, price, orderdate from grouptest
GROUP BY customer, price, orderdate

-- Shows ORDER BY multiple columns, separated by a comma.
SELECT CustomerID, LastName, COUNT(OrderID) FROM orderdetail 
GROUP BY LastName ORDER BY COUNT(OrderID), LastName ASC;