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

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.
主站蜘蛛池模板: 乐亭县| 桃江县| 安新县| 泽州县| 博野县| 伊金霍洛旗| 青浦区| 潞城市| 兴和县| 六枝特区| 沙坪坝区| 筠连县| 万州区| 阿城市| 土默特左旗| 香河县| 平武县| 米易县| 唐海县| 阿尔山市| 盐源县| 青铜峡市| 汾西县| 边坝县| 河北区| 隆化县| 农安县| 远安县| 鹤壁市| 赤城县| 饶平县| 闵行区| 迁安市| 定边县| 嘉义县| 南安市| 藁城市| 佛教| 靖西县| 收藏| 宜兰市|