Data Cube: A Relational Aggregation Operator Generalizing Group-By, Cross-Tab, and Sub-Totals

Jim Gray Microsoft [email protected] Adam Bosworth Microsoft [email protected] Andrew Layman Microsoft AndrewL@MicrosotLcom Hamid Pirahesh IBM [email protected]

Abstract: Data analysis applications typ&ally aggregate points such as temperature, pressure, humidity, and wind data across many dimensions looking for unusual patterns. velocity. Often these measured values are aggregates over The SQL aggregate functions and the GROUP BY operator time (the hour) or space (a measurement area). produce zero-dimensional or one-dimensional answers. Applications need the N-dimensional generalization of Table l:Weather these operators. This paper defines that operator, called Time (UCT) Latitude Longitude %ititude Tem; Pres the data cube or simply cube. The cube operator general- (m) (c) (mb) 27/ii/94:150( 37:58:33N 122:45:28W 102 21 1009 izes the histogram, cross-tabulation, roll-up, drill-down, 27/ii/94:150( 34:16:18N 27:05:55W" I0 23 11024 and sub-total constructs found in most report writers. The cube treats each of the N aggregation attributes as a di- The SQL standard provides five functions to aggregate the mension of N-space. The aggregate of a particular set of values in a table: COUNT ( ), SUM ( ), MIN ( ), ~ ( ), attribute values is a point in this space. The set of points and AVG(). For example, the average of all measured forms an N-dimensional cube. Super-aggregates are com- temperatures is expressed as: puted by aggregating the N-cube to lower dimensional SELECT AVG (Temp) spaces. Aggregation points are represented by an "infinite FROM Weather; value", ALL, so the point (ALL,ALL,...,ALL, sum(*)) repre- sents the global sum of all items. Each ALL value actually In addition, SQL allows aggregation over distinct values. represents the set of values contributing to that aggrega- The following query counts the distinct number of report- tion. ing times in the Weather table: SELECT COUNT (DISTINCT Time) I. Introduction FROM Weather; Many SQL systems add statistical functions (, stan- Data analysis applications look for unusual patterns in data. dard deviation, variance, etc.), physical functions (center They summarize data values, extract statistical information, of mass, angular momentum, etc.), financial analysis and then contrast one category with another. There are two (volatility, Alpha, Beta, etc.), and other domain-specific steps to such data analysis: functions, extracting the aggregated data from the into a file or table, and Some systems allow users to add new aggregation func- visualizing the results in a graphical way. tions. The Illustra system, for example, allows users to Visualization tools display trends, clusters, and differences. add aggregate functions by adding a program with the The most exciting work in data analysis focuses on pre- following three callbacks to the database system [lilustra]: senting new graphical metaphors that allow people to dis- Init (&handle) : Allocates the handle and initializes cover data trends and anomalies. Many tools represent the the aggregate computation. dataset as an N-dimensional space. Two and three- Iter (&handle, value) : Aggregates the next value dimensional sub-slabs of this space are rendered as 2D or into the current aggregate. 3D objects. Color and time (motion) add two more dimen- value, = Final (&handle) : Computes and returns the sions to the display giving the potential for a 5D display. resulting aggregate by using data saved in the handle. This invocation deallocates the handle. How do traditional relational fit into this picture? How can flat files (SQL tables) possibly model an N- Consider implementing the Average() function. The dimensional problem? Relational systems model N- handle stores the count and the sum initialized to zero. dimensional data as a relation with N-attribute domains. When passed a new non-null value, Iter ( ) increments the For example, 4-dimensional earth-temperature data is typi- cally represented by a Weather table shown below. The count and adds the sum to the value. The Final () call first four columns represent the four dimensions: x, y, z, t. dealiocates the handle and returns sum divided by count. Additional columns represent measurements at the 4D

152 1063-6382/96 $5.00 © 1996 IEEE Aggregate functions return a single value. Using the Red Brick also offers three cumulative aggregates that GROUP lay construct, SQL can also create a table of many operate on ordered tables. aggregate values indexed by a set of attributes. For exam- Oamulative (expression) : Sums all values so far in ple, The following query reports the average temperature an ordered list. for each reporting time and altitude: Running_Sum (expression, n) : Sums the most recent n SELECT Time, Altitude, gVG(Temp) values in an ordered list. The initial n-1 values are FROM Weather NULL. GROUP BY Time, Altitude; Runnlng_Average (expression, n) : Averages the GROUP BY is an unusual relational operator: It partitions most recent n values in an ordered list. The initial n-1 the relation into disjoint tuple sets and then aggregates over values are mv.~L. each set as illustrated in Figure 1. These aggregate functions are optionally reset each time a grouping value changes in an ordered selection. Aggregate Values I--] 2. Problems With GROUP BY" I--1 SQL's aggregation functions are widely used. In the spirit of aggregating data, Table 2 shows how frequently the database and transaction processing benchmarks use ag- gregation and GROUP Be. Surprisingly, aggregates also appear in the online-transaction processing TPC-C query Figure !: The GROUP BY relational operator partitions a set. Paradoxically, the TPC-A and TPC-B benchmark table into groups. Each group is then aggregated by a transactions spend most of their energies maintaining ag- function. The aggregation function summarizes some col- gregates dynamically: they maintain the summary bank umn of groups returning a value for each group. account balance, teller cash-drawer balance, and branch balance. All these can be computed as aggregates from the history table [TPC]. Red Brick systems added some interesting aggregate func- tions that enhance the GROUP BY mechanism [Red Brick]: Table 2: SQL Aggregates in Standard Benchmarks Rank (expression): returns the expression's rank in the Benchmark Queries Aggregates GROUPBYs set of all values of this domain of the table. If there are TPC-A, B 1 0 0 TPC-C 18 N values in the column, and this is the highest value, 4 0 TPC-D 16 27 15 the rank is N, if it is the lowest value the rank is 1. Wisconsin ! 8 3 2 N_tile(expression, n): The range of the expression AS3Ap 23 20 2 (over all the input values of the table) is computed and divided into n value ranges of approximately equal SetQuery 7 5 I population. The function returns the number of the range holding the value of the expression. If your The TPC-D query set has one 6D GROUP BY and three 3D bank account was among the largest 10% then your GROUP BYS. ID and 2D GROUP BYS are most common. rank (account.balance, 10) would return 10. Red Brick providesjust N_tile (expression, 3). Certain forms of data analysis are difficult if not impossi- Ratio To Total (expression): Sums all the expres- ble with the SQL constructs. As explained next, three sions and then divides the expression by the total sum. common problems are: (1) Histograms, (2) Roll-up Totals and Sub-Totals for drill-downs, (3) Cross Tabulations. To give an example: SELECT Percentile, MIN (Temp) ,MAX (Temp) The standard SQL GROUP BY operator does not allow a FROM Weather direct construction of histograms (aggregation over com- GROUP BY N_tile (Temp, 10) as Percentile puted categories.) For example, for queries based on the HAVING Percentile = 5; Weather table, it would be nice to be able to group times returns one row giving the minimum and maximum tem- into days, weeks, or months, and to group locations into peratures of the middle 10% of all temperatures. As men- areas (e.g., US, Canada, Europe,...). This would be easy if tioned later, allowing function values in the GROUP BY is function values were allowed in the GROUP BY list. If that not yet allowed by the SQL standard.

153 we~ allowed, the following query would give the daily Table 4: Sales Summary maximum reportedtemperamre. Model Year Color Units SELECT day, nation, MAX(Temp) Chevy 1994 black 50 FROM Weather GROUP BY Day(Time) AS day, Chevy 1994 white 40 Country(Latitude,Longitude) Chevy 1994 ALL 90 AS nation; Chevy 1995 black 85 Chevy 1995 white I 15 Some SQL systems support histograms but the standard Chevy 1995 ALL 200 does not. Rather, one must construct a table-valued expres- Chevy ALL ALL 290 sion and then aggregate over the resulting table. The fol- lowing statement demonstrates this SQL92 construct. The SQL stmement to build ~is SalesSummary table SELECT day, nation, MAX(Temp) from the raw Sales data is: FROM ( SELECT Day(Time) AS day, Country (Latitude, Longitude) SELECT Model, ALL, ALL, SUM(Sales) AS nation, FROM Sales Temp WHERE Model = 'Chevy' FROM Weather ) AS foo GROUP BY Model GROUP BY day, nation; UNION SELECT Model, Year, ALL, SUM(Sales) A second problem relates to roll-ups using totals and sub- FROM Sales totals for drill-down reports. Reports commonly aggregate WHERE Model = 'Chevy' GROUP BY Model, Year data at a coarse level, and then at successively finer levels. UNION The car sales report in Table 3 shows the idea. Data is ag- SELECT Model, Year, Color, SUM(Sales) gregated by Model, then by Year, then by Color. The re- FROM Sales port shows data aggregated at three levels. Going up the WHERE Model = 'Chevy' levels is called rolling-up the data. Going down is called GROUP BY Model, Year, Color; drilling-down into the data. This is a simple 3-dimensional roll-up. Aggregating over N dimensions ~qui~s N such unions. Table 3: Sales Roll Up by Model by Year by Color Sales Sales Sales Roll-up is asymmetric - notice that the table above does Model Year Color by Model by Model by Model not aggregate the sales by year. It lacks the rows aggre- by Year by Year gating sales by color rather than by year. These rows are: by Color Model Year Color Units Chevy 1994 black 50 Chevy black 135 white 40 ALL 90 Chevy ALL white 155 1995 black 85 white I 15 These additional rows could be captured by adding the 200 following clause to the SQL statement above: 290 UNION SELECT Model, ALL, Color, SUM(Sales) Table 3 is not relational -null values in the primary key are FROM Sales not allowed. It is also not convenient -- the number of col- WHERE Model = 'Chevy' GROUP BY Model, Color; umns grows as the power set of the number of aggregated attributes. Table 4 is a relational and more convenient rep- The symmetric aggregation result is a table called a cross- resentation. The dummy value "ALL" has been added to fill tabulation, or cross tab for short ( and some in the super-aggregation items. desktop databases call them pivot tables.) Cross tab data is routinely displayed in the more compact format of Table 5. Table 5: Chevy Sales Cross Tab This cross tab is a two-dimensional aggregation. If other Chevy i994 1995 total (ALL! automobile models are added, it becomes a 3D aggrega- black 50 85 135 tion. For example, data for Ford products adds an addi- white 40 115 155 tional cross tab plane as in Table 5.a. total (ALL) 90 200 290

154 Aggregate r--1 Table 5a: Ford Sales Cross Tab Sum GroupBy Ford 1994 1995 total (ALL) (with total) black 50 85 135 RED ~r °l°r WHITE white 10 75 85 BLUE total (ALL) 60 ! 60 220 r--1 Sum Cross Tab The cross tab array representation is equivalent to the rela- RED WHITE tional representation using the ALL value. Both generalize BLUE to an N-dimensional cross tab. By Make ~ ['-'7 The Data Cube and Sum The Sub-Space Aggregates The representation of Table 4 and unioned GROUP BYS "solve" the problem of representing aggregate data in a Y~.,~* By Make relational data model. The problem remains that express- By Make& Year []~ ~ ~-t ing histogram, roll-up, drill-down, and cross-tab queries RED with conventional SQL is daunting. A 6D cross-tab re- "q't'l ~ P~ BLUE ByColor & YearX4/4 | L,'/ quires a 64-way union of 64 different GROUP BY operators / II By Make& Color to build the underlying representation. Incidentally, on Sum By Color most SQL systems this will result in 64 scans of the data, Figure 2: The CUBE operator is the N-dimensional gener- 64 sorts or hashes, and a long wait. alization of simple aggregate functions. The 0D data cube is a point. The I D data cube is a line with a point. The 2D Building a cross-tabulation with SQL is even more daunt- data cube is a cross tab, a plane, two lines, and a point. The ing since the result is not a really a relational object - the 3D data cube is a cube with three intersecting 2D cross tabs. bottom row and the right column are "unusual". Most re- port writers build in a cross-tabs feature, building the report The next step is to allow decorations, columns that do not up from the underlying tabular data such as Table 4 and its appear in the GROUP BY but that are functionally depend- extension. See for example the TRANSFORM-PIVOT op- ent on the grouping columns. Consider the example: erator of Microsoft Access [Access]. SELECT department.name, sum(sales) FROM sales JOIN department USING (department_number) 3. The Data CUBE Operator GROUP BY sales .department_number;

The generalization of these ideas seems obvious: Figure 2 The department, name column in the answer set is not shows the concept for aggregation up to 3-dimensions. The allowed in current SQL, it is neither an aggregation col- traditional GROUP BY can generate the core of the N- umn (appearing in the GROUP BY list) nor is it an aggre- dimensional data cube. The N-I lower-dimensional aggre- gate. It is just there to decorate the answer set with the gates appear as points, lines, planes, cubes, or hyper-cubes name of the department. We recommend the rule that/fa hanging off the core data cube. decoration column (or column value) is functionally de- pendent on the aggregation columns, then it may be in- The data cube operator builds a table containing all these cluded in the SELECT answer list. aggregate values. The total aggregate is represented as the tuple: ALL, ALL, ALL..... ALL, f(*) These extensions are independent of the CUBE operator. Points in higher dimensional planes or cubes have fewer They remedy some pre-existing problems with GROUP BY. ALL values. Figure 3 illustrates this idea with an example. Some systems already allow these extensions, for example Microsoft Access allows function-valued GROUP BYS. We extend SQL's SELECT-GROUP-BY-HAVING syntax to support histograms, decorations, and the CUBE operator. Creating the CUBE requires generating the power set (set of Currently the SQL GROUP BY syntax is: GROUP BY all subsets) of the aggregation columns. We propose the ( [] .... } following syntax to extend SQL's GROUP BY operator: To support histograms, extend the syntax to: GROUP BY GROUP BY { ( I ) { ( I ) [ AS ] [ AS ] [ ]

[ ] • • . . } t .,. } [ WITH ( CUBE I ROLLUP ) ]

155 Thinking of the ALL value as a token representing these SELECT Model, Yeal, Colol, SL~4{sate=) AS Sales FROH Sales Is~IER£ H~del lh ('Fotd'. 'Chew)") sets defmes the semantics of the relational operators (e.g., i~q[, i'eal BETWEEN 1990 AND 1992 Chevy 192,O white 95 GROUP 9Y Model, ¥.al, Colol WITH CUBE; ch.vy 1~'9o ALL 154 eqxtals and IN). The ALL string is for display. A new Chevy 1991 blue 49 Chevy 1991 ~ed 54 ALL ( ) function generates the set associated with this value chevy 1~'91 white 95 Che v '. ] 99I ALL 198 they7 1 ~,~z blue 71 as in the examples above. ALL() applied to any other Ch~v ~' 1 "92 led 31 Ch~%' 19"= *¢ait. 54 value returns NULL. This design is eased by SQLYs sup- Chew V |%'92 ALL 156 Chev '." ALL blue 182 I' ~ALE:S Chevy ALL led 90 port for set-valued variables and domains. ModelYeat Color Sales :h~vy ALL white 236 i Ch~v ~." AI.L ALL 508 Fola 1.~*o blue 63 : chert 19"0 whit~ S7 Fol r| ] ,,!~o g ed 64 i Chev~ 199(~ blu6 ~ Fot.I 1990 white 62 The ALL value appears tO be essential, but creates substan- Chav3' 19!'1 I~d 54 Fold I',!,(I ALL 189 Chert 1991 white 95 Fold 1991 blue 55 tial complexity. It is a non-value, like NULL. We do not Chert l~q,1 J~l,,. 49 Fold 1991 red 5~ Fold 1991 white 9 Chert 19"2 Led 31 Fold 1991 ALL 116 add it lightly - adding it touches many aspects of the SQL Chevy 1992 white 54 Fold I!'92 blue )9 language. To name a few: Foe4 199(~ l~d 64 Fold 1992 whir 2 Fold 19!*(; white &= Fold 199~ ALL 128 • Treating each ALL value as the set of aggregates guides Fold ALL blue 157 ro~,~ ~99(] blue 63 Fold ALL led 143 1991 led Fol.~ 52 Fold ALL white 133 the meaning of the ALL value. Fold |991 wI,i t ~ 9 told ALL ALL 433 rot i 1991 blue ~,LL 19!,o biue 125 • ALL becomes a new keyword denoting the set value. Fold 19912 led ::7 ~LL 1990 zed 69 Fold 1 f,~,2 white B2 gLL 1990 whi t • 149 %LL 19~'0 ALL 313 • ALL [NOTI ALLOWEDis added to the column definition ~LL 1991 blue 106 %LL I~'91 led 104 %LL 1!,,,I whit. 1|o syntax and to the column attributes in the system ~.LL 19'q ALL 314 %LL 199".' blue 11o catalogs. %LL 1 P!'= ~ed 58 L,LL 1"9: white 116 • ALL, like NULL, does not participate in any aggregate hLL ] "92 ALL 284 kLL ALL blu* a3, %LL ALL led 223:, except COUNT (). gLL ALL white 369 %LL ALL ALL 941 • The set interpretation guides the meaning of the rela- Figure 3: A 3D data cube (right) built from the table at tional operators {=, <, <--, =, >=, >, IN}. the left by the CUBE statement at the top of the figure. There are more such rules, but this gives a hint of the added complexity. As an aside, to be consistent, if the ALL Figure 3 has an example of this syntax. To give another, value is a set then the other values of that domain must be he~ follows a statement to aggregate the set of ~mperature treated as singleton sets in order to have uniform operators observations: on the domain. SELECT day, nation, MAX(Tempi Decoration's interact with aggregate values. If the aggre- FROM Weather gate tuple functionally defines the decoration value, then GROUP BY Day(Time) AS day, the value appears in the resulting tuple. Otherwise the Country(Latitude, Longitude) decoration field is NULL. For example, in the following AS nation query the continent is not specified unless nation is. WITH CUBE; SELECT day,nation,MAX (Tempi, The semantics of the CUBE operator are that it first aggre- continent (nation) FROM Weather gates over all the