sql 第2行显示如何GROUP BY Last Name,然后ORDER BY两件事 - 首先是COUNT(OrderID),然后是LastName,在ASC ord中排序
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了sql 第2行显示如何GROUP BY Last Name,然后ORDER BY两件事 - 首先是COUNT(OrderID),然后是LastName,在ASC ord中排序相关的知识,希望对你有一定的参考价值。
-- 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;
以上是关于sql 第2行显示如何GROUP BY Last Name,然后ORDER BY两件事 - 首先是COUNT(OrderID),然后是LastName,在ASC ord中排序的主要内容,如果未能解决你的问题,请参考以下文章