Nod
Honorary Master
- Joined
- Jul 22, 2005
- Messages
- 10,057
Not sure if this fits in here, so feel free to move if needed.
Source: http://www.databasejournal.com/features/mysql/article.php/3865811/article.htm
Read further at the link above.
Source: http://www.databasejournal.com/features/mysql/article.php/3865811/article.htm
Today’s topic of discussion is crosstabs, which contain multiple aggregate functions in the row axis of a tabular resultset. Recall from the the All About the Crosstab Query article that an aggregate function is one that summarizes a group of related data in some way. Examples of aggregate functions include COUNT, SUM, AVG, MIN, and MAX. In a multi-aggregate crosstab query, two different functions can be applied to the same field or the same function can be applied to two or more fields. Today we'll create a query that applies two different functions to the same field in order to create grouping levels in the row axis.
Recap of Crosstab Basics
In the Tips for Simplifying Crosstab Query Statements article, we took the complex SQL statement that we created in the All About the Crosstab Query article and simplified it to a more streamlined version:
Code:SELECT CASE WHEN Month_Num IS NULL THEN 'TOTAL' ELSE Month END AS 'Month', REGION_1 AS 'REGION 1', REGION_2 AS 'REGION 2', REGION_3 AS 'REGION 3', REGION_4 AS 'REGION 4', REGION_5 AS 'REGION 5', TOTAL FROM (SELECT MONTH(CREATION_DATE) AS Month_Num, MONTHNAME(CREATION_DATE) AS Month, COUNT(CASE WHEN REGION_CODE ='01' THEN FEE_NUMBER END) AS REGION_1, COUNT(CASE WHEN REGION_CODE ='02' THEN FEE_NUMBER END) AS REGION_2, COUNT(CASE WHEN REGION_CODE ='03' THEN FEE_NUMBER END) AS REGION_3, COUNT(CASE WHEN REGION_CODE ='04' THEN FEE_NUMBER END) AS REGION_4, COUNT(CASE WHEN REGION_CODE ='05' THEN FEE_NUMBER END) AS REGION_5, COUNT(*) AS TOTAL FROM TA_CASES WHERE YEAR(CREATION_DATE)=1998 GROUP BY Month_Num WITH ROLLUP) AS CA;
The subquery fetched all of the fields that we needed, plus the month number, for sorting. We then selected from it by placing the code after the FROM of a second query. Performing a query in a two pass process in this way is called Pre (or Partial)-Aggregation. The first pass creates a derived table or resultset that performs most of the aggregation work, while the next pass does some formatting and any additional calculations that may be required. The neccessitating of pre-aggregation here was the result of two factors: The ROLLUP GROUP BY modifier inserted a Null row into the resultset, which was difficult to replace with the “TOTAL” row header because of its late evaluation in the query process. A second challenge was presented by the grouping on the output of date functions because grouping on the MONTHNAME() sorted the rows in alphabetical order, rather than chronological.
Read further at the link above.