官术网_书友最值得收藏!

GROUP BY

GROUP BY aggregates the results on the required column names or expressions. Building on the same example from the ORDER BY section, we want to know the overall product quantity per product name and location, from the following code snippet. The Quantity column is using the aggregate function SUM. Therefore, the remaining columns need to be contained in the aggregation GROUP BY clause:

SELECT P.Name AS ProductName, SUM([PI].Quantity) AS Total_Quantity, L.Name AS LocationName
FROM Production.Product AS P
INNER JOIN Production.ProductInventory AS [PI] ON P.ProductID = [PI].ProductID
INNER JOIN Production.Location AS L ON [PI].LocationID = L.LocationID
WHERE P.Name LIKE 'Touring%'
GROUP BY P.Name, L.Name
ORDER BY P.Name DESC, L.Name DESC;

The following screenshot shows the results with one row per set as defined by the GROUP BY clause:

Aggregations can be further specified by using the following keywords:

  • ROLLUP: Specifies the creation of subtotals and totals for the required column names or expressions.
  • CUBE: Specifies the creation of subtotals and totals for all combinations of columns in the GROUP BY clause.
  • GROUPING SETS: Allows the use of multiple GROUP BY clauses, such as using ROLLUP and CUBE together.
主站蜘蛛池模板: 樟树市| 奉化市| 右玉县| 哈巴河县| 莲花县| 岑巩县| 巴马| 嫩江县| 怀来县| 高邑县| 庄河市| 安溪县| 松桃| 佛坪县| 江孜县| 日照市| 屏南县| 溧水县| 新绛县| 台中市| 舞阳县| 明水县| 湘潭县| 商都县| 大新县| 上虞市| 连平县| 合水县| 甘南县| 儋州市| 宁南县| 望都县| 星子县| 石渠县| 新闻| 台州市| 云南省| 武强县| 婺源县| 始兴县| 忻城县|